package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.jpay.ext.kit.StrKit;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.*;
import com.qianniu.napi.admin.mapper.MdpayMapper;
import com.qianniu.napi.admin.mapper.OrderMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.*;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 订单
 * </p>
 *
 * @author chenxuebin
 * @since 2018-06-24
 */
@RestController
public class OrderController {

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsSkuService goodsSkuService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private IQnpay qnpay;
    @Autowired
    private IOrderGoodsService orderGoodsService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IMaccountService maccountService;
    @Autowired
    private IPintuanOpenService pintuanOpenService;
    @Autowired
    private IPintuanLogService pintuanLogService;
    @Autowired
    private ICouponService couponService;
    @Autowired
    private IJifenService jifenService;
    @Autowired
    private IOrderExtService orderExtService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IXnbiService xnbiService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IOrderRefundService refundService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ISmslogService smslogService;
    @Autowired
    private IMconfigExtService mconfigExtService;
    @Autowired
    private IChoujiangLogService choujiangLogService;
    @Autowired
    private IFenxiaoService fenxiaoService;
    @Autowired
    private MdpayMapper mdpayMapper;


    @RequestMapping("/api/pintuan/running")
    @ResponseBody
    public JsonDO pintuaning(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                             @RequestParam(value = "pageSize", required = false) int pageSize,
                             HttpServletRequest req) {
        JsonDO json = new JsonDO();
        List<PintuanOpen> list = pintuanOpenService.getPTOpenPage(ObjectUtil.getMid(), pageSize, pageIndex, 1);
        json.setData(list);
        return json;
    }

    @RequestMapping("/api/pintuan/will")
    @ResponseBody
    public JsonDO pintuanwill(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                              @RequestParam(value = "pageSize", required = false) int pageSize,
                              HttpServletRequest req) {
        JsonDO json = new JsonDO();
        List<PintuanOpen> list = pintuanOpenService.getPTOpenPage(ObjectUtil.getMid(), pageSize, pageIndex, 0);
        json.setData(list);
        return json;
    }

    @RequestMapping("/api/pintuan/list")
    @ResponseBody
    public JsonDO pintuanist(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                             @RequestParam(value = "pageSize", required = false) int pageSize,
                             @RequestParam(value = "status", required = false) int status,
                             HttpServletRequest req) {
        JsonDO json = new JsonDO();
        List<Order> list = orderService.getPTOrderGoodsPage(ObjectUtil.getUid(), pageSize, pageIndex, status);
        json.setData(list);
        return json;
    }

    @RequestMapping("/api/pintuan/olist")
    @ResponseBody
    public Jinfo pintuanolist(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                              @RequestParam(value = "pageSize", required = false) int pageSize,
                              @RequestParam(value = "status", required = false) int status,
                              HttpServletRequest req) {
        Jinfo json = new Jinfo();
        logger.info("==============status=" + status);
        List<Order> list = orderService.getPTOGoodsPage(ObjectUtil.getUid(), pageSize, pageIndex, status);
        for (Order o : list) {
            if (o.getPuid().longValue() == ObjectUtil.getUid().longValue()) {
                o.setIsowner(1);
            } else {
                o.setIsowner(-1);
            }
        }
        json.setInfo(list);
        return json;
    }

    //活动管理列表查询接口
    @RequestMapping("/api/huodong/olist")
    @ResponseBody
    public Jinfo huodongolist(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                              @RequestParam(value = "pageSize", required = false) int pageSize,
                              @RequestParam(value = "status", required = false) int status) {
        Jinfo json = new Jinfo();
        logger.info("-----------------status=" + status);
        List<Order> list = orderService.getHuodongPage(ObjectUtil.getUid(), pageSize, pageIndex, status);

        Date now = new Date();
        for (Order o : list) {
            //抽奖
            if (o.getType() == YXType.choujiang.getVal()) {
                o.setJps(choujiangLogService.selectList(new EntityWrapper<ChoujiangLog>()
                        .setSqlSelect("id,name,pic,level")
                        .eq("oid", o.getId()).eq("is_zhong", 1)));
            }

            //计算倒计时
            if (o.getEndtime() != null && now.getTime() < o.getEndtime().getTime()) {
                o.setTimeleft(DateUtil.getDatePoor(o.getEndtime(), now));
            }
        }

        json.setInfo(list);
        return json;
    }

    @RequestMapping("/api/pintuan/info")
    @ResponseBody
    public JsonDO pintuanInfo(@RequestParam(value = "gid", required = false) long gid,
                              @RequestParam(value = "oid", required = false) long oid,
                              HttpServletRequest req) {
        JsonDO json = new JsonDO();
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("gid", gid);
        Goods goods = goodsService.selectById(gid);
        map.clear();
        map.put("oid", oid);
        List<PintuanLog> plogs = pintuanLogService.selectByMap(map);

        PintuanOpen pintuanOpen = plogs.size() > 0 ? pintuanOpenService.selectOne(new EntityWrapper<PintuanOpen>().eq("id", plogs.get(0).getPtoid())) : new PintuanOpen();

        map.put("GroupUsers", plogs);
        map.put("FGInfo", pintuanOpen);
        Date now = new Date();
        if (pintuanOpen != null)
            map.put("ShowCountdownMilliseconds", pintuanOpen.getEndtime().getTime() - now.getTime());
        if (goods != null) map.put("pic", goods.getPic());

        map.put("uid", ObjectUtil.getUid());
//        if(pintuanOpen.getUid()==ObjectUtil.getUid()){
//            map.put("isowner", 1);
//        }else{
//            map.put("FGInfo", 0);
//        }
        json.setData(map);
        return json;
    }

    /*
     * 我的商城普通订单，实物商品
     * 普通商品订单，非活动订单，非买单订单
     */
    @RequestMapping("/api/order/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                      @RequestParam(value = "pageSize", required = false) int pageSize,
                      @RequestParam(value = "status", required = false) int status,
                      @RequestParam(value = "fhstate", required = false) Integer fhstate,
                      @RequestParam(value = "isadmin", required = false) Integer isadmin,
                      @RequestParam(value = "tuihuan", required = false) Integer tuihuan,
                      HttpServletRequest req) {
        Jinfo jinfo = new Jinfo();
        Map<String, Object> map = new HashMap<String, Object>();
        Long mpid = ObjectUtil.getMpid();
        if (ObjectUtil.getUid() == null) {
            jinfo.setCode(1);
            jinfo.setMsg("请授权登录后再查看");
            return jinfo;
        }
        String uid = ObjectUtil.getUid().toString();
        Page<Order> page = new Page<Order>(pageIndex, pageSize);

        Wrapper<Order> entity = new EntityWrapper<Order>()
                .setSqlSelect("id,status,pic,sid,sname,type,gtype,realpay,goods_name goodsName,refund_no refundNo,is_refund isRefund,order_no orderNo,order_type orderType,jifen,total,is_comment isComment")
                .eq("mpid", mpid)
                .eq("state", 1)
                .le("gtype", 2)
                .ge("gtype", 1)
                .le("type", 0)
                .ge("type", -1)
                .eq("is_deleted", -1);
//                .eq("is_deleted", 0).le("gtype", 2);
        if (isadmin == null) entity.eq("uid", uid);
        if (status == 3) {
            if (fhstate != null && fhstate == 1) entity.eq("status", status).eq("fhstate", fhstate);
            else if (fhstate != null && fhstate == 2) entity.eq("fhstate", fhstate);
            else if (fhstate == null) entity.eq("status", status);
        } else if (status == 99) {
        } else {
            entity.eq("status", status);
        }
        if (tuihuan != null && tuihuan == 1) {
            entity.eq("is_refund", 1);
        } else {
            entity.ne("is_refund", 1);
        }

        entity.orderBy("id", false);
        Page<Order> plist = orderService.selectPage(page, entity);
        if (plist == null || plist.getSize() == 0) {
            jinfo.setInfo(new ArrayList());
            return jinfo;
        }

        List<Order> orders = plist.getRecords();

        for (Order o : orders) {
            map.clear();
            map.put("oid", o.getId());
            o.setList(orderGoodsService.selectByMap(map));
            if (o.getIsRefund() == 1)
                o.setOrderRefund(refundService.selectOne(new EntityWrapper<OrderRefund>()
                        .setSqlSelect("id,realpay,refund,order_no orderNo,refund_no refundNo,status")
                        .eq("oid", o.getId())));
        }

        jinfo.setInfo(orders);
        return jinfo;
    }

    /*
     * 商户助手商户订单，实物商品
     * 普通商品订单，非活动订单
     */
    @RequestMapping("/api/order/mlist")
    @ResponseBody
    public Jinfo mlist(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                       @RequestParam(value = "pageSize", required = false) int pageSize,
                       @RequestParam(value = "status", required = false) int status,
                       @RequestParam(value = "fhstate", required = false) Integer fhstate,
                       @RequestParam(value = "tuihuan", required = false) Integer tuihuan) {
        Jinfo jinfo = new Jinfo();
        Map<String, Object> map = new HashMap<String, Object>();
        Long mpid = ObjectUtil.getMpid();
        MerchantConfig mconfig = redisService.getMconfig(mpid);
        Page<Order> page = new Page<Order>(pageIndex, pageSize);

        Wrapper<Order> entity = new EntityWrapper<Order>()
                .eq("mpid", mpid)
                .eq("state", 1)
                .le("gtype", 2)
                .eq("type", 0)
                .ne("status", StatusEnum.cancel.getVal())
                .eq("is_deleted", -1);
        if (mconfig.getShowForpay() == null || mconfig.getShowForpay() != 1) {
            entity.ne("status", StatusEnum.forpay.getVal());
        }

        if (status == 3) {
            entity.eq("status", status).eq("fhstate", fhstate);
        } else if (status == 99) {
        } else {
            entity.eq("status", status);
        }
        if (tuihuan != null && tuihuan == 1) {
            entity.eq("is_refund", 1);
        } else {
            entity.ne("is_refund", 1);
        }

        entity.orderBy("id", false);
        Page<Order> plist = orderService.selectPage(page, entity);
        if (plist == null || plist.getSize() == 0) {
            jinfo.setInfo(new ArrayList());
            return jinfo;
        }

        List<Order> orders = plist.getRecords();

        for (Order o : orders) {
            map.clear();
            map.put("oid", o.getId());
            o.setList(orderGoodsService.selectByMap(map));
            if (o.getIsRefund() == 1)
                o.setOrderRefund(refundService.selectOne(new EntityWrapper<OrderRefund>()
                        .setSqlSelect("id,realpay,refund,order_no orderNo,refund_no refundNo,status")
                        .eq("oid", o.getId())));
        }

        jinfo.setInfo(orders);
        return jinfo;
    }

    /*
     * 平台版商户订单，实物商城商品
     * 普通商品订单，非活动订单
     */
    @RequestMapping("/api/order/mchlist")
    @ResponseBody
    public Jinfo mchlist(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                         @RequestParam(value = "pageSize", required = false) int pageSize,
                         @RequestParam(value = "status", required = false) int status,
                         @RequestParam(value = "sid", required = false) Long sid,
                         @RequestParam(value = "fhstate", required = false) Integer fhstate,
                         @RequestParam(value = "tuihuan", required = false) Integer tuihuan) {
        Jinfo jinfo = new Jinfo();
        Map<String, Object> map = new HashMap<String, Object>();
        Long mpid = ObjectUtil.getMpid();
        MerchantConfig mconfig = redisService.getMconfig(mpid);
        Page<Order> page = new Page<Order>(pageIndex, pageSize);
        if (sid == null) sid = ObjectUtil.getSid();
        if (sid == null) {
            jinfo.setCode(1);
            jinfo.setMsg("参数有误");
            return jinfo;
        }

        Wrapper<Order> entity = new EntityWrapper<Order>()
                .eq("mpid", mpid)
                .eq("state", 1)
                .le("gtype", 2)
                .eq("type", 0)
                .eq("sid", sid)
                .eq("xftype", XftypeEnum.buy.getVal())
                .ne("status", StatusEnum.cancel.getVal())
                .eq("is_deleted", -1);

        Store store = redisService.getStore(sid);

        if (store.getShowforpay() == null || store.getShowforpay() != 1) {
            entity.ne("status", StatusEnum.forpay.getVal());
        }

        if (status == 3) {
            entity.eq("status", status).eq("fhstate", fhstate);
        } else if (status == 99) {
        } else {
            entity.eq("status", status);
        }

        if (tuihuan != null && tuihuan == 1) {
            entity.eq("is_refund", 1);
        } else {
            entity.ne("is_refund", 1);
        }

        entity.orderBy("id", false);
        Page<Order> plist = orderService.selectPage(page, entity);
        if (plist == null || plist.getSize() == 0) {
            jinfo.setInfo(new ArrayList());
            return jinfo;
        }

        List<Order> orders = plist.getRecords();

        for (Order o : orders) {
            map.clear();
            map.put("oid", o.getId());
            o.setList(orderGoodsService.selectByMap(map));
            if (o.getIsRefund() == 1)
                o.setOrderRefund(refundService.selectOne(new EntityWrapper<OrderRefund>()
                        .setSqlSelect("id,realpay,refund,order_no orderNo,refund_no refundNo,status")
                        .eq("oid", o.getId())));
        }

        jinfo.setInfo(orders);
        return jinfo;
    }


    /*
     * 【仟牛通商户管家】商家订单，需要发货配送都商品
     * 普通商品订单
     * 到店核销的订单不展示
     */
    @RequestMapping("/api/order/pslist")
    @ResponseBody
    public Jinfo pslist(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                        @RequestParam(value = "pageSize", required = false) int pageSize,
                        @RequestParam(value = "status", required = false) int status,
                        @RequestParam(value = "fhstate", required = false) Integer fhstate,
                        @RequestParam(value = "tuihuan", required = false) Integer tuihuan) {
        Jinfo jinfo = new Jinfo();
        Map<String, Object> map = new HashMap<String, Object>();
        Long mpid = ObjectUtil.getMpid();
        MerchantConfig mconfig = redisService.getMconfig(mpid);
        Page<Order> page = new Page<Order>(pageIndex, pageSize);

        Wrapper<Order> entity = new EntityWrapper<Order>()
                .eq("mpid", mpid)
                .eq("state", 1)
                .le("gtype", 2)
                .eq("type", 0)
                .ne("status", StatusEnum.cancel.getVal())
                .eq("is_deleted", -1);
        if (mconfig.getShowForpay() == null || mconfig.getShowForpay() != 1) {
            entity.ne("status", StatusEnum.forpay.getVal());
        }

        if (status == 3) {
            entity.eq("status", status).eq("fhstate", fhstate);
        } else if (status == 99) {
        } else {
            entity.eq("status", status);
        }
        if (tuihuan != null && tuihuan == 1) {
            entity.eq("is_refund", 1);
        } else {
            entity.ne("is_refund", 1);
        }

        entity.orderBy("id", false);
        Page<Order> plist = orderService.selectPage(page, entity);
        if (plist == null || plist.getSize() == 0) {
            jinfo.setInfo(new ArrayList());
            return jinfo;
        }

        List<Order> orders = plist.getRecords();

        for (Order o : orders) {
            map.clear();
            map.put("oid", o.getId());
            o.setList(orderGoodsService.selectByMap(map));
            if (o.getIsRefund() == 1)
                o.setOrderRefund(refundService.selectOne(new EntityWrapper<OrderRefund>()
                        .setSqlSelect("id,realpay,refund,order_no orderNo,refund_no refundNo,status")
                        .eq("oid", o.getId())));
        }

        jinfo.setInfo(orders);
        return jinfo;
    }

    /*
     * 我的活动
     */
    @RequestMapping("/api/order/hdlist")
    @ResponseBody
    public Jinfo hdlist(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                        @RequestParam(value = "pageSize", required = false) int pageSize,
                        @RequestParam(value = "status", required = false) int status,
                        @RequestParam(value = "fhstate", required = false) Integer fhstate,
                        @RequestParam(value = "isadmin", required = false) Integer isadmin,
                        @RequestParam(value = "tuihuan", required = false) Integer tuihuan,
                        HttpServletRequest req) {

        Jinfo jinfo = new Jinfo();
        Map<String, Object> map = new HashMap<String, Object>();
        Long mpid = ObjectUtil.getMpid();
        Page<Order> page = new Page<Order>(pageIndex, pageSize);

        Wrapper<Order> entity = new EntityWrapper<Order>()
                .eq("mpid", mpid)
                .eq("state", 1)
                .gt("type", 1)
                .eq("uid", ObjectUtil.getUid())
                .eq("is_deleted", 0);

        if (status < 99) entity.eq("status", status);
//        if (isadmin == null) entity.eq("uid", uid);

//        if (fhstate != null && fhstate == 1) entity.eq("fhstate", fhstate);
//        if (fhstate != null && fhstate == 2) entity.eq("fhstate", fhstate);

//        if (tuihuan != null && tuihuan == 1) {
//            entity.eq("is_refund", 1);
//        } else {
//            entity.ne("is_refund", 1);
//            if (status != 99) {
//                entity.eq("status", status);
//            }
//        }

        entity.orderBy("order_no", false);
        Page<Order> plist = orderService.selectPage(page, entity);
        logger.debug(">>>plist=" + JSON.toJSONString(plist));
        if (plist == null || plist.getSize() == 0) {
            jinfo.setInfo(new ArrayList());
            return jinfo;
        }

        List<Order> orders = plist.getRecords();
        logger.debug(">>>orders 1=" + JSON.toJSONString(orders));

        jinfo.setInfo(orders);
        return jinfo;
    }

    /*
     * 我的预约列表
     */
    @RequestMapping("/api/order/list2")
    @ResponseBody
    public Jinfo list2(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                       @RequestParam(value = "pageSize", required = false) int pageSize,
                       @RequestParam(value = "status", required = false) int status) {
        Jinfo json = new Jinfo();
        if (ObjectUtil.getUid() == null) {
            json.setCode(1);
            json.setMsg("未授权登录无法访问");
            return json;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("mpid", ObjectUtil.getMpid());

        Page page = new Page(pageIndex, pageSize);

        //普通预约项目
        Wrapper<Order> entity = new EntityWrapper<Order>()
                .ne("is_deleted", 1)
                .eq("state", 1)
                .le("type", 0)
                .ge("type", -1)
                .ge("gtype", 3)
                .le("gtype", 4)
                .eq("uid", ObjectUtil.getUid());

        if (status != 99) entity.eq("status", status);
        entity.orderBy("order_no", false);
        page = orderService.selectPage(page, entity);

        List<Order> list = page.getRecords();
        for (Order item : list) {
            if (item.getStatus() == -1) {
                item.setStatusStr("已关闭");
            } else if (item.getStatus() == 0) {
                item.setStatusStr("已取消");
            } else if (item.getStatus() == 1) {
                item.setStatusStr("待支付");
            } else if (item.getStatus() == 2) {
                item.setStatusStr("待确认");
            } else if (item.getStatus() == 3) {
                item.setStatusStr("待服务");
            } else if (item.getStatus() == 4) {
                item.setStatusStr("待评价");
            } else if (item.getStatus() == 5) {
                item.setStatusStr("已完成");
            }
        }

        json.setInfo(list);
        return json;
    }

    @RequestMapping("/api/order/pay")
    @ResponseBody
    public Jinfo orderPay(@RequestParam("id") Long id, HttpServletRequest req) {
        Jinfo json = new Jinfo();
        Order order = orderService.selectById(id);
        if (order == null) {
            json.setCode(4);
            json.setMsg("order not found");
            return json;
        }
        json.setInfo(orderService.getPaymap(order, false, "在线支付"));
        return json;
    }

    @RequestMapping("/api/pintuan/pay")
    @ResponseBody
    public JsonDO rechargePay(@RequestParam("on") String on,
                              HttpServletRequest req) {
        JsonDO json = new JsonDO();
        Order order = orderService.selectOne(new EntityWrapper<Order>().eq("order_no", on));
        if (order == null) {
            json.setCode(1);
            return json;
        }
        json.setData(orderService.getPaymap(order, false, "在线拼团支付"));
        return json;
    }

    // 买单接口，
    // 支持积分抵扣+支持券抵扣+会员折扣+余额抵扣多种抵扣
    @RequestMapping("/api/order/mdan")
    @ResponseBody
    public Jinfo mdan(@RequestParam("money") BigDecimal money,
                      @RequestParam("remark") String remark,
                      @RequestParam(value = "realpay", required = false) BigDecimal realpay,
                      @RequestParam(value = "ma", required = false) String ma,
                      @RequestParam(value = "zke", required = false) BigDecimal zke,
                      @RequestParam(value = "bi", required = false) Integer bi,
                      @RequestParam(value = "bikou", required = false) BigDecimal bikou,
                      @RequestParam(value = "yue", required = false) BigDecimal yue,
                      @RequestParam(value = "jfkou", required = false) BigDecimal jfkou,
                      @RequestParam(value = "quanid", required = false) Long quanid,
                      @RequestParam(value = "quankou", required = false) BigDecimal quankou,
                      @RequestParam("zftype") Integer zftype
    ) {
        logger.debug("--------------------------------------order/mdan come 000");

        Jinfo json = new Jinfo();
        if (zftype < 1 || zftype > 9) {
            json.setCode(1);
            json.setMsg("请求参数错误");
            return json;
        }
        if (money == null || money.doubleValue() <= 0) {
            json.setCode(1);
            json.setMsg("请求参数错误");
            return json;
        }

        Long mid = ObjectUtil.getMid();
        Long mpid = ObjectUtil.getMpid();
        Long uid = ObjectUtil.getUid();
        boolean nocash = zftype == 9 || realpay.doubleValue() <= 0;
        logger.debug("--------------------------------------order/mdan come 1111");

        MerchantConfig mconfig = redisService.getMconfig();
        Account ac = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
        if (yue != null && yue.doubleValue() > 0) {// 会员支付
            if (ac.getAmount().add(ac.getMamount()).subtract(yue).doubleValue() < 0) {
                json.setCode(2);
                json.setMsg("会员账户余额不足");
                return json;
            }
        }
        logger.debug("--------------------------------------order/mdan come 222");

        BigDecimal zero = new BigDecimal(0);
        Order order = new Order();
        Address address = addressService.selectOne(new EntityWrapper<Address>().eq("uid", uid).eq("is_default", 1));
        if (address != null) {
            order.setLinkman(address.getLinkman());
            order.setPhone(address.getPhone());
            order.setAddress(address.getAddress());
        } else {
            User user = userService.selectById(uid);
            order.setLinkman(user.getNickName());
            order.setPhone(user.getPhone() == null ? "" : user.getPhone());
            order.setAddress(user.getCity() == null ? "" : user.getCity());
        }

        order.setOrderNo(StringUtil.getSnNo("M"));
        order.setShortno(orderService.getShortno(ObjectUtil.getMpid()));

        if (mconfig.getShortno() != null && mconfig.getShortno() == 1) {
            String shortday = DateUtil.getShortToday().substring(4);
            int cout = orderService.selectCount(new EntityWrapper<Order>().eq("mpid", order.getMpid())
                    .like("order_no", DateUtil.getShortToday()).ge("status", 2)) + 1;
            shortday = shortday + cout;
            order.setShortno(shortday);
        }
        order.setPayType(PaytypeEnum.weixin.getVal());
        order.setGoodsName(order.getLinkman() + "到店自助买单");
        order.setGoodsNumber(1);

        order.setPrices(money);
        order.setTotal(money);

        order.setDeduction(yue);    // 余额折扣

        order.setMemberDiscount(zke == null ? zero : zke);// 会员折扣
        order.setBie(bi == null ? 0 : bi);//虚拟币跟人民币默认1：1关系
        order.setBikou(bikou == null ? zero : bikou);
        order.setJifenDiscount(jfkou == null ? zero : jfkou);
        //积分抵扣额*积分倍率
        BigDecimal jifen = order.getJifenDiscount().multiply(new BigDecimal(mconfig.getJifenRate()));
        //===========积分抵扣取整=====待完善
        order.setJifen(jifen);

        order.setCouponDiscount(quankou == null ? zero : quankou);
        // ====待完善
        order.setDiscount(order.getMemberDiscount().add(order.getBikou()).add(order.getJifenDiscount()).add(order.getCouponDiscount()));
        logger.debug("--------------------------------------order/mdan come 333");

        order.setFantimeType(mconfig.getFantimeType());
        order.setRealpay(zftype != 9 ? realpay : new BigDecimal(0));
        order.setIsNeedLogistics(0);
        if (zftype < 9 && realpay.doubleValue() > 0)
            order.setStatus(StatusEnum.forpay.getVal());
        else
            order.setStatus(StatusEnum.forsend.getVal());

        if (!Strings.isNullOrEmpty(ma)) {
            String key = ObjectUtil.getMid() + ObjectUtil.getAppid() + ObjectUtil.getMpid();
            String txt = AesUtil.decrypt(ma, EncryptUtil.md5t16(key));
            String[] ywdata = txt.split("__");
            if (Strings.isNullOrEmpty(ywdata[6])) {
                json.setCode(2);
                json.setMsg("该用户未绑定到诊所商户用户");
                return json;
            }
            if (ywdata.length >= 7) {
                order.setSid(Long.parseLong(ywdata[6]));
                Store store = redisService.getStore(order.getSid());
                order.setSname(store == null ? null : store.getName());
                if (order.getSid() != null) order.setLeagueid(redisService.getLeagueid(order.getSid()));
            }
        }
//        order.setRemark("ma=" + ma);
        order.setTradecode("ma=" + ma);

        order.setState(1);

        order.setGoodsNumber(1);
        order.setOrderType(1);//买单类型@1：自己买单；2：他人买单
        order.setGtype(GtypeEnum.none.getVal());//产品类型：无
        order.setType(YXType.common.getVal());//营销类型：无
        order.setXftype(XftypeEnum.maidan.getVal());
        order.setUid(uid);
        order.setMid(mid);
        order.setMpid(ObjectUtil.getMpid());
        logger.debug("--------------------------------------order/mdan come 444");

        User user = redisService.getUser();
        Boolean flag = false;
        if (order.getRealpay().doubleValue() == 0) {

            //余额支付,默认不赠送积分
            AccountFlow af = new AccountFlow();

            af.setRemark(remark);
            af.setTradetime(new Date());
            af.setRemark("到店自助买单");//1:微信 2:余额 3:币 9:线下支付
            af.setState(1);
            af.setMid(mid);
            af.setMpid(ObjectUtil.getMpid());
            af.setUid(uid);
            af.setNickname(user.getNickName());
            af.setHeadimg(user.getAvatarPic());
            af.setPhone(user.getPhone());

            af.setCreatetime(new Date());
            af.setSn(order.getOrderNo());

            BigDecimal sac = ac.getAmount().subtract(yue).doubleValue() > 0 ? yue : ac.getAmount();
            BigDecimal mac = ac.getAmount().subtract(yue).doubleValue() > 0 ? zero : yue.subtract(ac.getAmount());

            af.setTotal(order.getTotal());
            af.setRealpay(order.getRealpay());
            af.setAmount(sac);
            af.setDikou(mac.add(order.getDiscount()));
            af.setIsConfirm(nocash ? 1 : -1);//线下支付
            af.setConfirmDate(new Date());
            af.setIotype(IotypeEnum.output.getVal());
            af.setXftype(XftypeEnum.maidan.getVal());// 线下付款买单

            af.setLasttotal(ac.getTotal());
            af.setLastamount(ac.getAmount());
            af.insert();

            Account nbean = new Account();
            while (!flag && nocash) {

                Long version = ac.getVersion();
                BigDecimal amount = ac.getAmount();
                BigDecimal mamount = ac.getMamount();

                nbean.setAmount(amount.subtract(sac));
                nbean.setTotal(ac.getTotal().subtract(sac).subtract(mac));
                nbean.setMamount(mamount.subtract(mac));

                nbean.setModifytime(new Date());
                nbean.setModifier(uid);
                nbean.setVersion(version + 1);

                // ******* 更新账户表 ********
                flag = accountService.update(nbean, new EntityWrapper<Account>().eq("uid", af.getUid()).eq("version", version));
                logger.debug(">>>mdan accountService.update flag=" + flag);
                if (!flag) ac = accountService.selectOne(new EntityWrapper<Account>().eq("uid", af.getUid()));
            }
        }
        logger.debug("--------------------------------------order/mdan come 555");

        flag = false;
        if (nocash && jifen != null && jifen.doubleValue() > 0) {
            JifenFlow jifenflow = new JifenFlow();
            jifenflow.setConfirmDate(new Date());
            jifenflow.setCreatetime(new Date());
            jifenflow.setIotype(IotypeEnum.output.getVal());
            jifenflow.setIsConfirm(nocash ? 1 : -1);
            jifenflow.setJftype(XftypeEnum.dikou.getVal());

            jifenflow.setMid(mid);
            jifenflow.setMpid(mpid);
            jifenflow.setUid(uid);
            jifenflow.setNum(jifen);
            jifenflow.setSn(order.getOrderNo());
            jifenflow.setState(1);
            jifenflow.setRemark("ma=" + ma);
            jifenflow.insert();

            Jifen jf = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", uid));

            if (jf == null) jf = orderService.initJifen();
            Jifen xjf = new Jifen();

            while (!flag) {
                Long version = jf.getVersion();
                xjf.setTotal(jf.getTotal().subtract(jifen));
                xjf.setModifytime(new Date());
                xjf.setModifier(uid);
                xjf.setVersion(jf.getVersion() + 1);

                // ******* 更新账户表 ********
                flag = jifenService.update(xjf, new EntityWrapper<Jifen>().eq("uid", uid).eq("version", version));
                logger.debug(">>>mdan jifenService.update flag=" + flag);
                if (!flag) jf = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", uid));
            }
        }
        logger.debug("--------------------------------------order/mdan come 666");

        flag = false;
        if (nocash && bi != null && bi > 0) {
            XnbiFlow xflow = new XnbiFlow();
            xflow.setConfirmDate(new Date());
            xflow.setCreatetime(new Date());
            xflow.setIotype(IotypeEnum.output.getVal());
            xflow.setIsConfirm(zftype == 9 ? 1 : -1);
            xflow.setJftype(XftypeEnum.dikou.getVal());

            xflow.setMid(mid);
            xflow.setMpid(mpid);
            xflow.setUid(uid);
            xflow.setNum(new BigDecimal(bi));
            xflow.setSn(order.getOrderNo());
            xflow.setState(1);
            xflow.setRemark("ma=" + ma);
            xflow.insert();

            Xnbi xbi = xnbiService.selectOne(new EntityWrapper<Xnbi>().eq("uid", uid));
            if (xbi == null) xbi = orderService.initXnbi();
            Xnbi xxnbi = new Xnbi();
            while (!flag && nocash) {
                Long version = xbi.getVersion();
                xxnbi.setTotal(xbi.getTotal().subtract(new BigDecimal(bi)));
                xxnbi.setModifytime(new Date());
                xxnbi.setModifier(uid);
                xxnbi.setVersion(version + 1);

                // ******* 更新账户表 ********
                flag = xnbiService.update(xxnbi, new EntityWrapper<Xnbi>().eq("uid", uid).eq("version", version));
                logger.debug(">>>mdan accountService.update flag=" + flag);
                if (!flag) xbi = xnbiService.selectOne(new EntityWrapper<Xnbi>().eq("uid", uid));
            }
        }

        // ============ 无现金支付，实时消券============
        flag = false;
        if (quankou != null && quanid != null && nocash) {
            Coupon coupon = couponService.selectById(quanid);
            if (coupon != null) {
                coupon.setIsUsed(1);
                coupon.setIsUnused(0);
                coupon.updateById();
            }
        }

        logger.debug("======jfkou=" + jfkou);
        logger.debug("======bikou=" + bikou);
        logger.debug("======money=" + money);

        // ============ 消费后返现，根据消费额 ============
        BigDecimal fan = new BigDecimal(0);
        FanConfig fconfig = redisService.getFanconfig(mpid);
        if (fconfig.getMdfanType() != null && fconfig.getMdfanRatio() != null &&
                fconfig.getMdfanType() == 1 && (jfkou == null || jfkou.doubleValue() <= 0)
                && money.doubleValue() > 0
                && fconfig.getMdfanRatio().doubleValue() > 0) {
            logger.debug("--------------------------------------zgoufanjifen come");

            // 自购返积分
            fan = fconfig.getMdfanRatio().multiply(money).multiply(new BigDecimal(mconfig.getJifenRate()));// 1.23元*1(倍率)*1000积分换算
            order.setFanjifen(fan);

        } else if (fconfig.getMdfanType() == 3 && quanid == null) {
            // 自购返优惠券

        } else if (fconfig.getMdfanType() == 4 && (bikou == null || bikou.doubleValue() <= 0)
                && money.doubleValue() > 0
                && fconfig.getMdfanRatio().doubleValue() > 0) {

            logger.debug("======zgoufanbi come");
            // 自购返币
            fan = fconfig.getMdfanRatio().multiply(money);
            order.setFanbi(fan);
        }
        order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
        logger.debug("--------------------------------------order/mdan fenxiao panduan");
        if (order.getFxmode() == null && mconfig.getIsFenxiao() != null && mconfig.getIsFenxiao() == 1) {
            Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>()
                    .eq("mpid", order.getMpid()).eq("state", 1));
            logger.debug("--------------------------------------order/mdan fenxiao=" + JSON.toJSONString(fenxiao));
            if (fenxiao != null) order.setFxmode(Fxmode.common.getVal());
        }
        order.insert();
        logger.debug("--------------------------------------order/mdan come 999");

        if (order.getRealpay().doubleValue() > 0)
            json.setInfo(orderService.getPaymap(order, false, "在线买单支付"));

        return json;
    }


    @RequestMapping("/api/order/jyajin")
    @ResponseBody
    public Jinfo jyajin(@RequestParam("money") BigDecimal money, HttpServletRequest req) {
        Jinfo json = new Jinfo();

        Long mid = ObjectUtil.getMid();
        Long uid = ObjectUtil.getUid();

        BigDecimal zero = new BigDecimal(0);

        Order order = new Order();
        Address address = addressService.selectOne(new EntityWrapper<Address>().eq("uid", uid).eq("is_default", 1));
        if (address != null) {
            order.setLinkman(address.getLinkman());
            order.setPhone(address.getPhone());
            order.setAddress(address.getAddress());
        } else {
            User user = userService.selectById(uid);
            order.setLinkman(user.getNickName());
            order.setPhone(user.getPhone() == null ? "" : user.getPhone());
            order.setAddress(user.getCity() == null ? "" : user.getCity());
        }
        logger.info("===========jyajin order=" + JSON.toJSONString(order));

        order.setOrderNo(StringUtil.getSnNo("Y"));
        order.setShortno(orderService.getShortno(ObjectUtil.getMpid()));
        order.setPayType(PaytypeEnum.weixin.getVal());
        order.setGoodsName("在线交纳押金");
        order.setPrices(money);
        order.setTotal(money);
        order.setDiscount(zero);
        order.setRealpay(money);
        order.setIsNeedLogistics(0);
        order.setStatus(StatusEnum.finish.getVal());
        order.setState(1);
        order.setDeduction(zero);
        order.setOrderType(0);
        order.setGoodsNumber(1);
        order.setGtype(GtypeEnum.none.getVal());
        order.setType(YXType.common.getVal());//营销类型@ -1：积分购；0：普通商品； 1：拼团；2：砍价；3：抽奖；5：会员商品
        order.setXftype(XftypeEnum.jyajin.getVal());//营销类型@ 0：普通商品； 1：拼团；2：砍价；3：抽奖；4：积分购；5：会员商品
        order.setUid(uid);
        order.setMid(mid);
        order.setMpid(ObjectUtil.getMpid());
        order.setFantimeType(redisService.getMconfig().getFantimeType());
        order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
        order.insert();

        json.setInfo(orderService.getPaymap(order, false, "在线交纳押金"));

        return json;
    }

    // 商家退押金给客户（商家往里面充值）
    @RequestMapping("/api/order/tyajin")
    @ResponseBody
    public Jinfo tyajin(@RequestParam("guid") String guid, HttpServletRequest req,
                        @RequestParam("money") BigDecimal money) {
        Jinfo info = new Jinfo();

        String ip = ObjectUtil.getIP();
        Long mid = ObjectUtil.getMid();
        Long mpid = ObjectUtil.getMpid();
        Long uid = ObjectUtil.getUid();
        User user = redisService.getUser();

        Order order = new Order();
        order.setUid(uid);
        order.setMid(mid);
        order.setMpid(mpid);
        order.setRealpay(money);
        order.setPrices(money);
        order.setTotal(money);
        order.setStatus(1);
        order.setState(1);
        order.setOrderType(0);
        order.setPayType(2);
        order.setGoodsName("商家退押金给客户");
        order.setGoodsNumber(1);
        order.setXftype(XftypeEnum.tyajin.getVal());
        order.setGtype(GtypeEnum.none.getVal());
        order.setType(YXType.common.getVal());
        order.setLinkman(user.getNickName());
        order.setPhone(user.getPhone());
        order.setOrderNo(StringUtil.getSnNo("C"));
        order.setShortno(orderService.getShortno(ObjectUtil.getMpid()));
        BigDecimal zero = new BigDecimal(0);

        MaccountFlow maf = new MaccountFlow();
        maf.setUid(uid);
        maf.setMid(mid);
        maf.setState(1);
        maf.setIotype(IotypeEnum.input.getVal());//1:入账
        maf.setXftype(XftypeEnum.recharge.getVal());//1:充值
        maf.setAmount(money);
        maf.setMamount(zero);
        maf.setIsConfirm(-1);//未确认
        maf.setSn(StringUtil.getSnNo("R"));
        maf.setRemark("商家充值退押金");
        maf.setTradetime(new Date());
        maf.setCreatetime(maf.getTradetime());
        maf.insert();

        Map<String, String> map = qnpay.minappPay(mid, ObjectUtil.getAppid(), uid, money, maf.getRemark(), maf.getSn(), ip, order);
        if (!map.containsKey("package")) {
            info.setCode(1);
        }
        info.setInfo(map);

        return info;
    }

    //退押金
    @RequestMapping("/api/tyajin/confirm")
    @ResponseBody
    public Jinfo tyajinConfirm(@RequestParam("guid") String guid,
                               @RequestParam("money") BigDecimal money) {
        // 给客户转押金+商家减钱
        logger.info(">>>tyajinConfirm guid=" + guid);
        logger.info(">>>tyajinConfirm money=" + money);

        Jinfo info = new Jinfo();
        String rkey = Constants.REDIS_TYAJIN + guid;
        String ywdata = redisService.get(rkey);

        if (Strings.isNullOrEmpty(guid) || money == null) {
            info.setCode(4);
            info.setMsg("参数有误");
            return info;
        }
        if (Strings.isNullOrEmpty(ywdata) || ywdata.indexOf("__") == -1) {
            info.setCode(1);
            info.setMsg("找不到退款信息");
            return info;
        }
        String openid = ywdata.split("__")[0];
        BigDecimal rmoney = BigDecimal.valueOf(Double.valueOf(ywdata.split("__")[1]));

        if (money.doubleValue() != rmoney.doubleValue()) {
            info.setCode(1);
            info.setMsg("退款信息有误");
            return info;
        }

        User tuser = redisService.getUserByGuid(guid);
        Long uid = tuser.getId();
        Long mid = ObjectUtil.getMid();
        Long mpid = ObjectUtil.getMpid();

        Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));

        if (act == null) act = orderService.initAccount();
        if (act.getYajin().doubleValue() < money.doubleValue()) {
            info.setCode(1);
            info.setInfo("余额不足");
            return info;
        }
        // ******* 系统默认秒提现 ******* 待完善 实现商家自定义配置

        // ******* 客户更新流水+财务表 *******
        AccountFlow af = new AccountFlow();

        af.setRealpay(money);
        af.setDikou(new BigDecimal(0));
        af.setRealpay(new BigDecimal(0));
        af.setTotal(af.getRealpay().add(af.getAmount()).add(af.getDikou()));

        af.setXftype(XftypeEnum.tyajin.getVal());
        af.setIotype(IotypeEnum.output.getVal());// 系统默认秒提现

        af.setTradetime(new Date());
        User user = redisService.getUser();
        af.setNickname(user != null ? user.getNickName() : null);
        af.setHeadimg(user != null ? user.getAvatarPic() : null);
        af.setPhone(user != null ? user.getPhone() : null);

        af.setState(1);
        af.setRemark("用户退押金");
        af.setCreatetime(new Date());
        af.setMid(mid);
        af.setMpid(mpid);
        af.setUid(uid);
        af.setSn(StringUtil.getSnNo("T"));// 实现不同业务类型的流水号


        // ******* 商家财务+流水更新 *******
        Maccount mact = maccountService.selectOne(new EntityWrapper<Maccount>().eq("mid", mid));
        MaccountFlow maf = new MaccountFlow();

        maf.setAmount(money);

        maf.setXftype(XftypeEnum.tyajin.getVal());//退押金
        maf.setIotype(IotypeEnum.output.getVal());// 系统默认秒提现
        maf.setIsConfirm(-1);
        maf.setTradetime(new Date());
        maf.setState(1);
        maf.setRemark("商家确认退押金");
        maf.setCreatetime(new Date());
        maf.setMid(mid);
        maf.setMpid(af.getMpid());
        maf.setUid(ObjectUtil.getUid());
        maf.setSn(af.getSn());// 实现不同业务类型的流水号

        String ip = ObjectUtil.getIP();

        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }

        // ******* 微信支付实时退款 *******
        Map<String, String> map = qnpay.payPakect(mpid, ObjectUtil.getAppid(), tuser, money, "申请退款到零钱", ip);
        String return_code = map.get("return_code");
        String result_code = null;

        logger.info("========================payPakect map=" + JSON.toJSONString(map));
        if (("SUCCESS").equals(return_code)) {
            result_code = map.get("result_code");
            if (("SUCCESS").equals(result_code)) {
                //提现成功
                info.setCode(0);
                info.setInfo("提现成功");
                logger.info("========================tyajinConfirm OK and AccountFlow insert OK");
            } else {
                //提现失败
                info.setCode(1);
                info.setInfo(map.get("err_code_des"));
                return info;
            }
        }

        boolean flag = false;
        Account nbean = new Account();
        while (!flag) {
            act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
            Long version = act.getVersion();
            BigDecimal yajin = act.getYajin();
            BigDecimal total = act.getTotal();

            nbean.setYajin(yajin.subtract(money));
            nbean.setTotal(total.subtract(money));
            nbean.setModifytime(new Date());
            nbean.setModifier(uid);
            nbean.setVersion(version + 1);

            af.setConfirmDate(new Date());
            af.setIsConfirm(1);
            af.setRuzhang(1);
            af.setLasttotal(act.getTotal());
            af.setLastamount(act.getAmount());
            // ******* 更新账户表 ********
            flag = accountService.update(nbean, new EntityWrapper<Account>().eq("uid", af.getUid()).eq("version", version));
            logger.info(">>>tyajinConfirm accountService.update flag=" + flag);
            if (flag) af.insertOrUpdate();

        }

        flag = false;
        Maccount mbean = new Maccount();//退押金
        while (!flag) {
            mact = maccountService.selectOne(new EntityWrapper<Maccount>().eq("mid", mid));
            Long version = mact.getVersion();
            BigDecimal total = mact.getTotal();
            BigDecimal amount = mact.getAmount();
            BigDecimal sale = mact.getSaleAmount();

            // ******* 待完善 商户账户余额不足的情况处理 *********
//            if(money.doubleValue()> amount.doubleValue()){
//                json.setCode(1);
//                json.setInfo("当前余额不足");
//                return json;
//            }
            mbean.setTotal(total.subtract(money));
            mbean.setAmount(amount.subtract(money));
//          mbean.setSaleAmount(sale.subtract(money));//累计销售额只针对付款（销售+充值）

            mbean.setModifytime(new Date());
            mbean.setModifier(uid);
            mbean.setVersion(version + 1);

            maf.setConfirmDate(new Date());
            maf.setIsConfirm(1);
            maf.setLasttotal(mact.getTotal());
            maf.setModifytime(new Date());

            // ******* 更新账户表 ********
            flag = maccountService.update(mbean, new EntityWrapper<Maccount>().eq("mid", mid).eq("version", version));
            logger.info(">>>tyajinConfirm accountService.update flag=" + flag);
            if (!flag) {
                mact = maccountService.selectOne(new EntityWrapper<Maccount>().eq("mid", mid));
                maf.insertOrUpdate();
            }
        }
//        redisService.del(rkey);
        String rpkey = Constants.REDIS_TYAJIN + guid + "_ispay";
        redisService.set(rpkey, 1, 10, TimeUnit.MINUTES);
        return info;
    }

    @RequestMapping("/api/tyajin/query")
    @ResponseBody
    public Jinfo tyajinQuery() {

        Jinfo info = new Jinfo();
        String rpkey = Constants.REDIS_TYAJIN + redisService.getUser().getGuid() + "_ispay";
        String rkey = Constants.REDIS_TYAJIN + redisService.getUser().getGuid();
        Integer ok = redisService.get(rpkey);
        if (ok == null || ok != 1) {
            info.setCode(1);
        } else {
            info.setCode(0);
            redisService.del(rpkey);
            redisService.del(rkey);
        }
        return info;
    }

    @RequestMapping("/api/order/add")
    @ResponseBody
    public Jinfo orderAdd(Order order,
                          @RequestParam(value = "yydate", required = false) String yydate,
                          @RequestParam(value = "yytime", required = false) String yytime,
                          @RequestParam(value = "isDuihuan", required = false) Integer isDuihuan,
                          @RequestParam(value = "dhtype", required = false) Integer dhtype,
                          @RequestParam(value = "s", required = false) String scene,
                          @RequestParam(value = "o", required = false) String ori,
                          @RequestParam(value = "tmplIds", required = false) String tmplIds,
                          HttpServletRequest req) {
        logger.debug(">>>>>>>>>order/add=" + JSON.toJSONString(order));

        Jinfo json = new Jinfo();
        BigDecimal prices = new BigDecimal(req.getParameter("prices"));//商品总价格
        BigDecimal yunfei = new BigDecimal(req.getParameter("yunfei"));//运费
        BigDecimal total = new BigDecimal(req.getParameter("total"));//总价
        BigDecimal realpay = new BigDecimal(req.getParameter("realpay"));//总价

        String orderType = req.getParameter("orderType");
        logger.debug(">>>amountGoods=" + prices);
        logger.debug(">>>amountYunfei=" + yunfei);
        logger.debug(">>>amountTotle=" + total);
        logger.debug(">>>order=" + order);

        // yytime=[08:00-08:30]
        if (!Strings.isNullOrEmpty(yydate) && !Strings.isNullOrEmpty(yytime)) {
            logger.debug("======yytime=" + yytime);
            String[] yytimes = yytime.split("-");
            yytime = yytimes.length == 1 ? yytime + ":00" : yytimes[0] + ":00";
            order.setYyday(yydate.trim());
            order.setYytime(yytime);
        }

        // 生成订单
        Long uid = ObjectUtil.getUid();
        order.setUid(uid);
        order.setMid(ObjectUtil.getMid());
        order.setMpid(ObjectUtil.getMpid());
        order.setOrderNo(StringUtil.getSnNo("D"));// 订单编号
        order.setShortno(orderService.getShortno(ObjectUtil.getMpid()));

        order.setState(1);

        order.setPrices(prices);
        order.setYunfei(yunfei);
        order.setTotal(total);
        order.setRealpay(realpay);
        order.setXftype(XftypeEnum.buy.getVal());

        //订单来源
        if (!Strings.isNullOrEmpty(scene) || !Strings.isNullOrEmpty(ori)) {
            ori = scene + "@" + ori;
            order.setOri(ori);
            order.setFanuid(ObjectUtil.orderFanuid(ori));
        }

        MerchantConfig mconfig = redisService.getMconfig();
        order.setFantimeType(mconfig.getFantimeType());
        //配送方式
        order.setShipperMethod(mconfig.getPstype());

        if (order.getRealpay().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.weixin.getVal());
        } else if (order.getDeduction().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.deduction.getVal());
        } else {
            order.setPayType(PaytypeEnum.daofu.getVal());
        }

        order.setOrderType(0);//订单购买类型@0：默认；1：拼团；2：抽奖；4：砍价
        order.setIsComment(0);

        if (order.getRealpay().doubleValue() > 0) {
            order.setStatus(1);
        } else {
            order.setStatus(order.getGtype() == 1 ? 2 : 3);
        }

        BigDecimal discount = new BigDecimal(0);
        // discount = 活动优惠+券优惠+积分优惠+会员优惠
        if (order.getActivityDiscount() != null) {
            discount = discount.add(order.getActivityDiscount());
        }
        if (order.getCouponDiscount() != null) {
            discount = discount.add(order.getCouponDiscount());
        }
        if (order.getJifenDiscount() != null) {
            discount = discount.add(order.getJifenDiscount());
        }
        if (order.getMemberDiscount() != null) {
            discount = discount.add(order.getMemberDiscount());
        }
        order.setDiscount(discount);// 合计折扣

        order.setExpire(30);// 默认30分钟过期
        order.setCreatetime(new Date());

        BigDecimal fanjifen = new BigDecimal(0);// 返积分
        BigDecimal fanqian = fanjifen;// 代金券|现金
        BigDecimal fanbi = fanjifen;// 返币
        int type = 0;// 返币
        BigDecimal sharefan = new BigDecimal(0);// 普通分享奖励
        Long gid = null;
        Goods goods = null;
        if (!Strings.isNullOrEmpty(order.getGoodsJsonStr())) {
            JSONArray ja = JSON.parseArray(order.getGoodsJsonStr());// 订单商品
            logger.info(JSON.toJSONString(ja));

            logger.debug(">>>order=" + JSON.toJSONString(order));
            if (order.getId() == null) {
                order.setCreatetime(new Date());
//            order.insert();
            } else {
                order.setModifytime(new Date());
                order.updateById();
            }

            String title = "欢迎购买" + order.getGoodsName();

            for (int i = 0; i < ja.size(); i++) {
                JSONObject jo = ja.getJSONObject(i);
                OrderGoods og = new OrderGoods();
                if (i == 0 && jo.getLong("skuid") != null) {
                    order.setSkuid(jo.getLong("skuid"));
                    order.setSpec(jo.getString("label"));
                }

                og.setGid(jo.getLong("gid"));
                og.setSkuid(jo.getLong("skuid"));
                og.setSpec(jo.getString("label"));
                if (!Strings.isNullOrEmpty(og.getSpec())) og.setSpec(og.getSpec().replace("undefined", ""));
                if (i == 0) gid = og.getGid();

                goods = goodsService.selectById(og.getGid());
                if (goods.getXiangou() != null && goods.getXiangou().intValue() > 0) {
                    OrderGoods orderGoods =
                            orderGoodsService.selectOne(new EntityWrapper<OrderGoods>().setSqlSelect(" sum(number) number ").eq("gid", gid).eq("uid", uid));
                    if (orderGoods != null && orderGoods.getNumber() != null && orderGoods.getNumber().intValue() >= goods.getXiangou().intValue()) {
                        json.setCode(1);
                        json.setMsg("该活动商品限量购买，您已经购买了" + goods.getXiangou() + "份");
                        return json;
                    }
                }

                logger.debug(">>>goods=" + JSON.toJSONString(goods));
                logger.debug(">>>og=" + JSON.toJSONString(og));
                GoodsSku goodssku = og.getSkuid() != null && og.getSkuid() > 0 ? goodsSkuService.selectById(og.getSkuid()) : null;
                og.setGoodsName(goods.getName());

                if (goods.getZgfanType() == 1) {
                    fanjifen = fanjifen.add(new BigDecimal(goods.getZgfanMount()));
                } else if (goods.getZgfanType() == 2) {
                    fanqian = fanqian.add(new BigDecimal(goods.getZgfanMount()));
                } else if (goods.getZgfanType() == 4) {
                    fanbi = fanbi.add(new BigDecimal(goods.getZgfanMount()));
                }

                type = goods.getType();
                if (goods.getShareBonusType() > 0 && goods.getFxmode() >= 1) {
                    sharefan = sharefan.add(goods.getShareMount());
                }

                if (order.getId() == null && i == 0) {
                    order.setGoodsName(goods.getName());
                    if (order.getGtype() == null) order.setGtype(goods.getGtype());
                    order.setShareBonusType(goods.getShareBonusType());
                    order.setFantimeType(goods.getFantimeType() != null ? goods.getFantimeType() : redisService.getMconfig().getFantimeType());
                    order.setPic(Strings.isNullOrEmpty(goods.getThumb()) ? goods.getPic() : goods.getThumb());
                    order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
                    order.insert();
                }

                if (i == 0) {
                    title = "购买" + og.getGoodsName() + "订单";
                    og.setIsDefault(1);
                    order.setSupplyid(goods.getSupplyid());
                } else {
                    og.setIsDefault(0);
                }
                og.setNumber(jo.getInteger("number"));

                og.setSaleprice(jo.getBigDecimal("saleprice"));
                if (jo.containsKey("hyprice")) og.setHyprice(jo.getBigDecimal("hyprice"));
                og.setTotal(og.getSaleprice().multiply(new BigDecimal(og.getNumber())));
                og.setPrice(goodssku == null ? goods.getPrice() : goodssku.getPrice());
                og.setStatus(order.getStatus());// 订单状态
                og.setJifen(goods.getJifen());// 订单状态
                og.setState(1);// 订单状态
                og.setOrderType(Strings.isNullOrEmpty(orderType) ? 0 : Integer.valueOf(orderType));
                if (goods.getShareBonusType() > 0) {
                    og.setSharefan(goods.getShareMount().multiply(new BigDecimal(order.getGoodsNumber())));
                }
                og.setSpec(jo.getString("label"));
                if (!Strings.isNullOrEmpty(og.getSpec())) og.setSpec(og.getSpec().replace("undefined", ""));
                og.setPic(goodssku == null ? goods.getPic() : goodssku.getPic());

                og.setOid(order.getId());
                og.setGtype(goods.getGtype());

                og.setUid(order.getUid());
                og.setMid(order.getMid());
                og.setMpid(order.getMpid());
                og.setOrderNo(order.getOrderNo());
                og.setCreatetime(order.getCreatetime());
                logger.debug(">>>OrderGoods=" + JSON.toJSONString(og));
                og.insert();
            }
        } else {
            if (order.getId() == null) {
                order.setCreatetime(new Date());
                order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
//            order.insert();
            } else {
                order.setModifytime(new Date());
                order.updateById();
            }

            OrderGoods og = new OrderGoods();
            goods = goodsService.selectById(order.getGid());
            logger.debug("========goods=" + JSON.toJSONString(goods));
            if (goods.getXiangou() != null && goods.getXiangou().intValue() > 0) {
                OrderGoods orderGoods =
                        orderGoodsService.selectOne(new EntityWrapper<OrderGoods>().setSqlSelect(" sum(number) number ").eq("gid", gid).eq("uid", uid));
                if (orderGoods != null && orderGoods.getNumber() != null && orderGoods.getNumber().intValue() >= goods.getXiangou().intValue()) {
                    json.setCode(1);
                    json.setMsg("该活动商品限量购买，您已经购买了" + goods.getXiangou() + "份");
                    return json;
                }
            }
            GoodsSku goodssku = null;
            og.setGid(order.getGid());
            gid = og.getGid();

            // 普通分享奖励模式
            if (goods.getShareBonusType() != null && goods.getShareBonusType() > 0
                    && goods.getFxmode() != null && goods.getFxmode() >= 1) {
                og.setSharefan(goods.getShareMount().multiply(new BigDecimal(order.getGoodsNumber())));
                sharefan = sharefan.add(goods.getShareMount());
            }
//            if (goods.getType() != null && goods.getType() > 0) type = goods.getType();
            type = goods.getType();

            if (order.getSkuid() != null && order.getSkuid() > 0) {
                goodssku = goodsSkuService.selectById(order.getSkuid());
                og.setNumber(order.getGoodsNumber());
                og.setSaleprice(goodssku.getSaleprice());
                og.setPrice(goodssku.getPrice());
                og.setSpec(goodssku.getCharacteristic());

            } else if (order.getGid() != null && order.getGid() > 0) {

                og.setNumber(order.getGoodsNumber());
                og.setPrice(goods.getPrice());
                og.setSaleprice(goods.getSaleprice());
                og.setHyprice(goods.getHyprice());
                og.setSpec(goods.getCharacteristic());
            }

            logger.debug(">>>og=" + JSON.toJSONString(og));

            og.setGoodsName(goodssku == null ? goods.getName() : goodssku.getName());
            Store store = redisService.getStore(order.getSid());
            order.setSname(store == null ? null : store.getName());

            if (order.getId() == null) {
                order.setSupplyid(goods.getSupplyid());
                order.setGoodsName(og.getGoodsName());
                if (order.getGtype() == null) order.setGtype(goods.getGtype());
                order.setShareBonusType(goods.getShareBonusType());
                order.setFantimeType(goods.getFantimeType() != null ? goods.getFantimeType() : redisService.getMconfig().getFantimeType());
                order.setPic(goodssku == null ? Strings.isNullOrEmpty(goods.getThumb()) ? goods.getPic() : goods.getThumb() : goodssku.getPic());
                order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
                order.insert();
            }

            og.setIsDefault(1);

            og.setPic(goodssku == null ? goods.getPic() : goodssku.getPic());

            og.setTotal(og.getSaleprice().multiply(new BigDecimal(og.getNumber())));
            og.setPrice(goodssku == null ? goods.getPrice() : goodssku.getPrice());

            og.setStatus(order.getStatus());// 订单状态
            og.setJifen(goods.getJifen());// 订单状态
            og.setState(1);// 订单状态
            og.setOrderType(Strings.isNullOrEmpty(orderType) ? 0 : Integer.valueOf(orderType));

            og.setOid(order.getId());
            og.setGtype(goods.getGtype());

            if (goods.getZgfanType() == 1) {
                fanjifen = fanjifen.add(new BigDecimal(goods.getZgfanMount()));
            } else if (goods.getZgfanType() == 2) {
                fanqian = fanqian.add(new BigDecimal(goods.getZgfanMount()));
            } else if (goods.getZgfanType() == 4) {
                fanbi = fanbi.add(new BigDecimal(goods.getZgfanMount()));
            }

            og.setUid(order.getUid());
            og.setMid(order.getMid());
            og.setMpid(order.getMpid());
            og.setOrderNo(order.getOrderNo());
            og.setCreatetime(order.getCreatetime());
            logger.debug(">>>OrderGoods=" + JSON.toJSONString(og));
            og.insert();
        }

        order.setGid(gid);
        order.setFanjifen(fanjifen);
        order.setSharefan(sharefan);
        order.setFanbi(fanbi);
        order.setFanqian(fanqian);
        if (order.getType() == null) order.setType(YXType.common.getVal());

        if (order.getGtype().intValue() == 1 && (order.getShipperMethod() == null || order.getShipperMethod() == 0))
            order.setShipperMethod(1);

        if (order.getFxmode() == null && mconfig.getIsFenxiao() != null && mconfig.getIsFenxiao() == 1) {
            Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>().eq("mpid", order.getMpid()).eq("state", 1));
            if (fenxiao != null) order.setFxmode(Fxmode.common.getVal());
        }
        order.updateById();
        if (!Strings.isNullOrEmpty(tmplIds)) {
            AkkaServer.system.actorOf(Props.create(TemplatemsgActor.class))
                    .tell("AddTplform@" + order.getId() + "@" + tmplIds, ActorRef.noSender());
        }

        // ======= 订单已支付后 =======
        logger.debug("============order=" + JSON.toJSONString(order));
        if (order.getRealpay().doubleValue() > 0) {
            json.setInfo(orderService.getPaymap(order, false, "在线支付购买"));
        } else {
            //非支付情况
            order.setTransactionId("0");
            if (order.getStatus() >= 2) {

                processPayAccoumt(order, isDuihuan, dhtype);
            } else {
                logger.error(">>>>>>>>>>>>>>>>>>>>>>>>order unprocess logic");
                json.setInfo(order);
            }
        }

        return json;
    }

    //平台版多商家普通商品下单接口
    @RequestMapping("/api/order/sadd")
    @ResponseBody
    public Jinfo orderSAdd(Order order,
                           @RequestParam(value = "yydate", required = false) String yydate,
                           @RequestParam(value = "yytime", required = false) String yytime,
                           @RequestParam(value = "s", required = false) String scene,
                           @RequestParam(value = "o", required = false) String ori,
                           HttpServletRequest req) {
        logger.debug("---------------------------------------order/sadd=" + JSON.toJSONString(order));

        Jinfo json = new Jinfo();
        BigDecimal prices = new BigDecimal(req.getParameter("prices"));//商品总价格
        BigDecimal yunfei = new BigDecimal(req.getParameter("yunfei"));//运费
        BigDecimal total = new BigDecimal(req.getParameter("total"));//总价
        BigDecimal realpay = new BigDecimal(req.getParameter("realpay"));//总价

        String orderType = req.getParameter("orderType");
        logger.debug(">>>amountGoods=" + prices);
        logger.debug(">>>amountYunfei=" + yunfei);
        logger.debug(">>>amountTotle=" + total);
        logger.debug(">>>order=" + order);

        if (ObjectUtil.getUid() == null) {
            json.setCode(1);
            json.setMsg("请授权登录之后再操作");
            return json;
        }

        // yytime=[08:00-08:30]
        if (!Strings.isNullOrEmpty(yydate) && !Strings.isNullOrEmpty(yytime)) {
            logger.debug("======yytime=" + yytime);
            String[] yytimes = yytime.split("-");
            yytime = yytimes.length == 1 ? yytime + ":00" : yytimes[0] + ":00";
            order.setYytime(yytime);
            order.setYyday(yydate.trim());
        }

        // 生成订单
        Long uid = ObjectUtil.getUid();
        order.setUid(uid);
        User user = redisService.getUser();
        order.setHeadimg(user.getAvatarPic());
        order.setMid(ObjectUtil.getMid());
        order.setMpid(ObjectUtil.getMpid());

        order.setState(1);
        if (order.getRealpay().doubleValue() > 0) {
            order.setStatus(1);
        } else {
            order.setStatus(order.getGtype() == 1 ? 2 : 3);
        }

        order.setPrices(prices);
        order.setYunfei(yunfei);
        order.setTotal(total);
        order.setRealpay(realpay);
        order.setOrderNo(StringUtil.getSnNo("D"));// 订单编号

        //订单来源
        if (!Strings.isNullOrEmpty(scene) || !Strings.isNullOrEmpty(ori)) {
            ori = scene + "@" + ori;
            order.setOri(ori);
            order.setFanuid(ObjectUtil.orderFanuid(ori));
        }

        if (order.getRealpay().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.weixin.getVal());
        } else if (order.getDeduction().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.deduction.getVal());
        } else if (order.getPayType() == null) {
            order.setPayType(PaytypeEnum.daofu.getVal());
        }

        order.setOrderType(1);//订单支付类型@1：自己支付；2：他人支付
        order.setIsComment(0);

        BigDecimal zero = new BigDecimal(0);
        BigDecimal discount = new BigDecimal(0);
        // discount = 活动优惠+券优惠+积分优惠+会员优惠
        if (order.getActivityDiscount() != null) {
            discount = discount.add(order.getActivityDiscount());
        }
        if (order.getCouponDiscount() != null) {
            discount = discount.add(order.getCouponDiscount());
        }
        if (order.getJifenDiscount() != null) {
            discount = discount.add(order.getJifenDiscount());
        }
        if (order.getMemberDiscount() != null) {
            discount = discount.add(order.getMemberDiscount());
        }
        order.setDiscount(discount);// 合计折扣
        order.setExpire(30);// 默认30分钟过期
        order.setCreatetime(new Date());
        order.setXftype(XftypeEnum.buy.getVal());

        BigDecimal fanjifen = new BigDecimal(0);// 返积分
        BigDecimal fanqian = fanjifen;// 代金券|现金
        BigDecimal fanbi = fanjifen;// 返币

        BigDecimal minprice = zero;// 普通分享奖励
        BigDecimal sharefan = zero;
        BigDecimal ptfan = zero;
        BigDecimal lmfan = zero;
        BigDecimal allsaleprice = zero;

        Long gid = null;
        Goods goods = null;

        if (!Strings.isNullOrEmpty(order.getGoodsJsonStr())) {
            JSONArray ja = JSON.parseArray(order.getGoodsJsonStr());// 订单商品
            logger.info(JSON.toJSONString(ja));

            for (int i = 0; i < ja.size(); i++) {

                JSONObject jo = ja.getJSONObject(i);
                OrderGoods og = new OrderGoods();

                og.setGid(jo.getLong("gid"));
                og.setSid(jo.getLong("sid"));
                og.setSkuid(jo.getLong("skuid"));
                og.setSpec(jo.getString("label"));
                og.setNumber(jo.getInteger("number"));
                BigDecimal ognum = new BigDecimal(og.getNumber());
                if (!Strings.isNullOrEmpty(og.getSpec())) og.setSpec(og.getSpec().replace("undefined", ""));
                if (i == 0) gid = og.getGid();

                goods = goodsService.selectById(og.getGid());

                if (goods.getXiangou() != null && goods.getXiangou().intValue() > 0) {
                    OrderGoods orderGoods =
                            orderGoodsService.selectOne(new EntityWrapper<OrderGoods>().setSqlSelect(" sum(number) number ").eq("gid", gid).eq("uid", uid));
                    if (orderGoods != null && orderGoods.getNumber() != null && orderGoods.getNumber().intValue() >= goods.getXiangou().intValue()) {
                        json.setCode(1);
                        json.setMsg("您已经购买了限购商品" + goods.getName() + goods.getXiangou() + "份");
                        return json;
                    }
                }

                logger.debug(">>>goods=" + JSON.toJSONString(goods));
                logger.debug(">>>og=" + JSON.toJSONString(og));
                GoodsSku goodssku = og.getSkuid() != null && og.getSkuid() > 0 ? goodsSkuService.selectById(og.getSkuid()) : null;
                og.setGoodsName(goods.getName());

                if (goods.getZgfanType() == 1) {
                    fanjifen = fanjifen.add(new BigDecimal(goods.getZgfanMount()).multiply(ognum));
                } else if (goods.getZgfanType() == 2) {
                    fanqian = fanqian.add(new BigDecimal(goods.getZgfanMount()).multiply(ognum));
                } else if (goods.getZgfanType() == 4) {
                    fanbi = fanbi.add(new BigDecimal(goods.getZgfanMount()).multiply(ognum));
                }

                //普通分享模式佣金计算
                if (goods.getShareBonusType() != null && goods.getShareBonusType() != 0 &&
                        goods.getShareMount() != null && goods.getShareMount().doubleValue() > 0 &&
                        goods.getFxmode() != null && goods.getFxmode().intValue() == 2) {

                    int cout = orderService.selectCount(new EntityWrapper<Order>().eq("gid", order.getGid())
                            .eq("is_refund", -1).gt("status", 1));//该商品 && 无退货 && 已支付
                    logger.debug("-------------------------cout=" + cout);
                    logger.debug("-------------------------goods.getFenxiaoshu().intValue()=" + goods.getFenxiaoshu());
                    if (goods.getFenxiaoshu() == null || cout < goods.getFenxiaoshu().intValue())
                        sharefan = sharefan.add(goods.getShareMount().multiply(ognum));
                }
                lmfan = lmfan.add(goods.getLmfan().multiply(ognum));
                ptfan = ptfan.add(goods.getPtfan().multiply(ognum));
                allsaleprice = allsaleprice.add(goods.getSaleprice().multiply(ognum));

                if (order.getId() == null && i == 0) {
                    order.setGoodsName(goods.getName());
                    order.setGtype(goods.getGtype());
                    order.setFantimeType(redisService.getMconfig().getFantimeType());
                    order.setPic(Strings.isNullOrEmpty(goods.getThumb()) ? goods.getPic() : goods.getThumb());
                    order.insert();
                }

                if (i == 0) {
                    og.setIsDefault(1);
                } else {
                    og.setIsDefault(0);
                }


                og.setSaleprice(jo.getBigDecimal("saleprice"));
                if (jo.containsKey("hyprice")) og.setHyprice(jo.getBigDecimal("hyprice"));
                og.setTotal(og.getSaleprice().multiply(new BigDecimal(og.getNumber())));
                og.setPrice(goodssku == null ? goods.getPrice() : goodssku.getPrice());
                og.setStatus(order.getStatus());// 订单状态
                og.setJifen(goods.getJifen());// 订单状态
                og.setState(1);// 订单状态
                og.setOrderType(Strings.isNullOrEmpty(orderType) ? 0 : Integer.valueOf(orderType));
                if (goods.getShareBonusType() > 0) {
                    og.setSharefan(goods.getShareMount().multiply(new BigDecimal(order.getGoodsNumber())));
                }
                og.setSpec(jo.getString("label"));
                if (!Strings.isNullOrEmpty(og.getSpec())) og.setSpec(og.getSpec().replace("undefined", ""));
                og.setPic(goodssku == null ? goods.getPic() : goodssku.getPic());

                og.setOid(order.getId());
                og.setGtype(goods.getGtype());

                og.setUid(order.getUid());
                og.setMid(order.getMid());
                og.setMpid(order.getMpid());
                og.setOrderNo(order.getOrderNo());
                og.setCreatetime(order.getCreatetime());
                logger.debug(">>>OrderGoods=" + JSON.toJSONString(og));
                og.insert();
            }
        }

        order.setGid(gid);
        order.setFanjifen(fanjifen);
        order.setFanbi(fanbi);
        order.setFanqian(fanqian);
        order.setType(YXType.common.getVal());

        goods = goodsService.selectById(gid);
        //入驻商家订单

        order.setSid(goods.getSid());
        order.setLeagueid(redisService.getLeagueid(goods.getSid()));
        order.setOrderNo(StringUtil.getSnNo("D"));// 订单编号
        order.setShortno(orderService.getStoreShortno(ObjectUtil.getMpid(), order.getSid()));

        Store store = redisService.getStore(order.getSid());
        order.setSname(store == null ? null : store.getName());
        if (store == null) {
            json.setCode(1);
            json.setMsg("该商家不存在");
            return json;
        }

        //如果对于普通商品
        //如果未填报配送方式
        //===配送方式@0：虚拟课程，无配送；1：快递包邮；2：外卖配送；3：商家配送；4：自提|到店核销&
        Integer pstype = order.getShipperMethod();//自提|到店|核销
        if (pstype == null) pstype = store.getPstype();//自提|到店|核销
        if (pstype == null) pstype = 4;
        if (order.getShipperMethod() == null && order.getGtype() == 1) {
            if (order.getSid() != null) {
                pstype = store.getPstype();
            } else {
                pstype = pstype;
            }
        } else if (order.getShipperMethod() == null && order.getGtype() == 2) {
            //虚拟课程，不退款
            pstype = 0;
        }
        order.setShipperMethod(pstype);
        order.setFantimeType(pstype < 4 ? FantimeType.confirm.getVal() : FantimeType.hexiao.getVal());//电商商品默认需要配送
        //配送方式
        order.setShipperMethod(store.getPstype());

        //分销返利类型
        order.setShareBonusType(goods.getShareBonusType());//分销返利类型

        //根据配送方式类型确定返佣金触发时机
        //对于实物发货类型，返佣金在【确认】时出发
        //对于到店核销类型，返佣金在【核销】时出发
        order.setFantimeType(pstype == 0 ? FantimeType.payok.getVal() : pstype == 1 ? FantimeType.confirm.getVal() :
                pstype == 2 ? FantimeType.confirm.getVal() : pstype == 3 ? FantimeType.songda.getVal() :
                        pstype == 4 ? FantimeType.hexiao.getVal() : FantimeType.payok.getVal());

        logger.debug("-------------------------sharefan=" + sharefan);
        Mdpay mdpay = mdpayMapper.selectById(order.getSid());
        if (mdpay == null) mdpay = mdpayMapper.selectById(-order.getMpid());
        if (lmfan.add(ptfan).doubleValue() >= order.getRealpay().doubleValue()) {
            ptfan = order.getRealpay().multiply(mdpay.getPayplat());
            lmfan = order.getRealpay().multiply(mdpay.getPaymeng());
            if (sharefan.doubleValue() > 0) sharefan = order.getRealpay().multiply(mdpay.getPayshare());
            minprice = order.getRealpay().subtract(ptfan).subtract(lmfan).subtract(sharefan);
        } else {
            minprice = order.getRealpay().subtract(ptfan).subtract(lmfan).subtract(sharefan);
        }

        logger.debug("-------------------------ptfan=" + ptfan);
        logger.debug("-------------------------lmfan=" + lmfan);
        logger.debug("-------------------------minprice=" + minprice);
        logger.debug("-------------------------sharefan=" + sharefan);

        order.setMinprice(minprice);//分享奖励类型@0：无奖励；1：送积分；2：送现金；3：送优惠券；4：送虚拟币；
        order.setLmfan(lmfan);//分享奖励类型@0：无奖励；1：送积分；2：送现金；3：送优惠券；4：送虚拟币；
        order.setPtfan(ptfan);//分享奖励类型@0：无奖励；1：送积分；2：送现金；3：送优惠券；4：送虚拟币；

        //促销成本计算，优先保证商家成本
        //minprice==针对入驻商家的成本
        logger.debug("-------------------------order.getSid()=" + order.getSid());
        logger.debug("-------------------------goods.getMinPrice()=" + goods.getMinPrice());
        logger.debug("-------------------------order.getSid()=" + order.getSid());
        logger.debug("-------------------------order.getGoodsNumber()=" + order.getGoodsNumber());

        //普通分享奖励
        if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.common.getVal()) {
            order.setSharefan(sharefan);//分享奖励类型@0：无奖励；1：送积分；2：送现金；3：送优惠券；4：送虚拟币；
            //非普通分销，推广佣金单独算
        } else if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.fexiao.getVal()) {
            //非平台入驻商家，商家自营的，
            // 且有分享奖金+奖励模式是分销模式，在支付成功生成订单时处理

        } else if (goods.getFxmode() != null && goods.getFxmode() == Fxmode.jieti.getVal()) {
            //===待完善
            //非平台入驻商家，商家自营的，
            // 且有分享奖金+奖励模式是阶梯模式

        }
        MerchantConfig mconfig = redisService.getMconfig(order.getMpid());
        if (order.getFxmode() == null && mconfig.getIsFenxiao() != null && mconfig.getIsFenxiao() == 1) {
            Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>().eq("mpid", order.getMpid()).eq("state", 1));
            if (fenxiao != null) order.setFxmode(Fxmode.common.getVal());
        }

        order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
        order.updateById();

        // ======= 订单已支付后 =======
        logger.debug("============order=" + JSON.toJSONString(order));
        if (order.getRealpay().doubleValue() > 0) {
            json.setInfo(orderService.getPaymap(order, false, "在线支付购买"));
        } else {
            order.setTransactionId("0");
            if (order.getStatus() >= 2) {
                processPayAccoumt(order, null, null);
            } else {
                logger.debug(">>>>order unprocess logic");
                json.setInfo(order);
            }
        }

        return json;
    }

    //付费推广
    @RequestMapping("/api/pyq/addpay")
    @ResponseBody
    public Jinfo pyqAddpay(@Valid Pyq pyq,
                           HttpServletRequest req) {
        Jinfo info = new Jinfo();

        User user = redisService.getUser();
        if (ObjectUtil.getUid() == null) {
            info.setCode(1);
            info.setMsg("当前用户未登陆");
            return info;
        }
        //===待实现，接单之后，更新标记
        pyq.setCreatetime(new Date());
        pyq.setMid(ObjectUtil.getMid());
        pyq.setMpid(ObjectUtil.getMpid());
        pyq.setUid(ObjectUtil.getUid());
        pyq.setState(-1);
        pyq.setStatus(1);
        pyq.setSid(ObjectUtil.getSid());

        if (ObjectUtil.getSid() != null) {
            Store store = storeService.selectById(ObjectUtil.getSid());
//            pyq.setPhone(store.getPhone());
            if (pyq.getLat() == null) pyq.setLat(store.getLatitude());
            if (pyq.getLat() == null) pyq.setLng(store.getLongitude());
            pyq.setMname(store.getName());
            pyq.setMlogo(store.getLogo() == null ? user.getAvatarPic() : store.getLogo());
            pyq.setMaddr(store.getAddress());
        } else {
            User ruser = redisService.getUser();
//            pyq.setPhone(ruser.getPhone());
            pyq.setMname(ruser.getNickName());
            pyq.setMlogo(ruser.getAvatarPic());
        }

        try {
            logger.info("=========pyq=" + JSON.toJSONString(pyq));
            pyq.insert();

            //删除之前未支付订单

            Order order = new Order();
            order.setOrderNo(StringUtil.getSnNo("P"));
            order.setShortno(orderService.getShortno(ObjectUtil.getMpid()));
            order.setGid(pyq.getId());

            order.setGoodsName("用户" + user.getNickName() + "发单");
            order.setXftype(XftypeEnum.paidan.getVal());
            order.setGtype(GtypeEnum.xu.getVal());
            order.setType(YXType.common.getVal());
            order.setPrice(pyq.getMoney());
            order.setPrices(pyq.getMoney());
            order.setDeduction(new BigDecimal(0));

            order.setSaleprice(pyq.getMoney());
            order.setTotal(pyq.getMoney());

            //平台默认提取服务费==促销成本=接单费=发单费用*promotionCost
            MerchantConfig mconfig = redisService.getMconfig();
            order.setMinprice(pyq.getMoney().multiply(mconfig.getPromotionCost()));
            order.setRealpay(pyq.getMoney());
            order.setDiscount(new BigDecimal(0));

            order.setLinkman(pyq.getMname());
            order.setAddress(pyq.getAddress());
            order.setPhone(pyq.getPhone());
            order.setPic(pyq.getPic().split(";")[0]);

            order.setPayType(PaytypeEnum.weixin.getVal());
            order.setOrderType(1);
            order.setStatus(1);
            order.setState(-1);
            order.setGoodsNumber(1);
            order.setIsNeedLogistics(-1);
            order.setFantimeType(FantimeType.after7days.getVal());

            order.setHeadimg(user.getAvatarPic());
            order.setUid(pyq.getUid());
            order.setMpid(pyq.getMpid());
            order.setMid(pyq.getMid());
            order.setCreatetime(new Date());
            order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
            order.insert();

            // ======= 订单已支付后 =======
            logger.debug("============order=" + JSON.toJSONString(order));
            if (pyq.getMoney().doubleValue() > 0) {
                info.setInfo(orderService.getPaymap(order, false, "在线支付派单活动"));
            }

        } catch (Exception e) {
            logger.error("======pyq.insert error", e);
        }
        return info;
    }

    @RequestMapping("/api/order/yymodify")
    @ResponseBody
    public Jinfo yymodify(Order order,
                          @RequestParam(value = "yydate", required = true) String yydate,
                          @RequestParam(value = "yytime", required = true) String yytime) {
        Jinfo json = new Jinfo();
        if (order == null || order.getId() == null) {
            json.setCode(1);
            json.setMsg("参数有误");
            return json;
        }

        // yytime=[08:00-08:30]
        if (!Strings.isNullOrEmpty(yydate) && !Strings.isNullOrEmpty(yytime)) {
            logger.debug("======yytime=" + yytime);
            String[] yytimes = yytime.split("-");
            yytime = yytimes.length == 1 ? yytime + ":00" : yytimes[0] + ":00";
            order.setYyday(yydate.trim());
            order.setYytime(yytime);
        }
        logger.info("----------------------------------------------------------------------------yymodify order=" + order);
        orderService.updateById(order);
        if (order.getStatus() == StatusEnum.forpay.getVal()) {
            json.setInfo(orderService.getPaymap(orderMapper.selectById(order.getId()), true, "在线预约支付订单"));
        }

        return json;
    }

    @RequestMapping("/api/order/repay")
    @ResponseBody
    public Jinfo orderAdd(@RequestParam("oid") Long oid) {
        Jinfo json = new Jinfo();
        if (oid == null) {
            json.setCode(1);
            json.setMsg("参数有误");
            return json;
        }

        Order order = orderService.selectById(oid);
        if (order == null) {
            json.setCode(4);
            json.setMsg("订单不存在");
            return json;
        }
        if (order.getStatus() == 0) {
            json.setCode(4);
            json.setMsg("订单已关闭");
            return json;
        }
        if (order.getStatus() == -1) {
            json.setCode(4);
            json.setMsg("订单已取消");
            return json;
        }

        //判断是否订单超时
        Date now = new Date();
        if (now.getTime() - order.getCreatetime().getTime() >= 30 * 60 * 1000) {
//            json.setCode(1);
//            json.setMsg("订单已过期，请重新下单");
//            return json;
            String oldOrderNo = order.getOrderNo();
            order.setOrderNo(StringUtil.getSnNo());
            order.setPrepayid(null);
            OrderGoods og = new OrderGoods();
            og.setOrderNo(order.getOrderNo());
            og.setModifytime(new Date());

            orderGoodsService.update(og, new EntityWrapper<OrderGoods>().eq("oid", oid));

            json.setInfo(orderService.getRepaymap(order, "在线支付订单", oldOrderNo));

        } else {
            json.setInfo(orderService.getPaymap(order, true, "在线支付订单"));
        }

        return json;
    }

    @RequestMapping("/api/order/modify")
    @ResponseBody
    public JsonDO addrUpdate(@Valid Order order,
                             BindingResult bindingResult, HttpServletRequest req) {
        JsonDO json = new JsonDO();
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            json.setMsg("There are errors! " + bindingResult);
            json.setCode(400);
            return json;
        }
        order.setModifytime(new Date());
        order.updateById();
        return json;
    }

    @RequestMapping("/api/order/cancel")
    @ResponseBody
    public Jinfo cancelOrder(@RequestParam("oid") Long oid, HttpServletRequest req) {
        Jinfo json = new Jinfo();
        Map<String, Object> map = null;
        if (oid == null) {
            json.setCode(1);
            json.setMsg("请求参数错误");
            return json;
        }
        Order order = orderService.selectById(oid);
        if (order == null) {
            json.setCode(4);
            json.setMsg("该订单不存在");
            return json;
        }
        // 商家秒退
        if (order.getStatus() < 1 || order.getStatus() > 3) {
            json.setCode(1);
            json.setMsg("当前不支持取消订单操作");
            return json;
        }

        if (Strings.isNullOrEmpty(order.getRefundNo())) {
            order.setRefundNo(StringUtil.getSnNo("R"));
            order.setIsRefund(1);
        }
        // 生成订单取消申请
        OrderRefund or = new OrderRefund();
        or.setRealpay(order.getRealpay());
        or.setRefund(order.getRealpay());
        or.setOid(order.getId());
        or.setOrderNo(order.getOrderNo());
        order.setShortno(orderService.getShortno(ObjectUtil.getMpid()));
        or.setRefundNo(order.getRefundNo());
        or.setRemark("申请取消订单");
        or.setStatus(1);// 默认受理中
        or.setState(1);

        String ip = ObjectUtil.getIP();
        or.setIp(ip);// 默认受理中

        or.setUid(order.getUid());
        or.setMid(order.getMid());
        or.setMpid(order.getMpid());
        or.setCreatetime(new Date());
        or.insert();

        MerchantConfig mc = redisService.getMconfig();
        Boolean tui = false;
        if (order.getStatus() == 1) {
            order.setStatus(StatusEnum.cancel.getVal());
            order.updateById();

            OrderGoods og = new OrderGoods();
            og.setStatus(StatusEnum.cancel.getVal());
            og.setOid(order.getId());
            orderGoodsService.update(og, new EntityWrapper<OrderGoods>().eq("oid", order.getId()));

        } else if (mc.getIsMiaotui() == 1 && order.getRealpay().doubleValue() > 0 &&
                (order.getStatus() == 2 || (order.getStatus() == 3 && order.getGtype() > 1))) {
            // 退款
            map = qnpay.cancelOrder(order, ObjectUtil.getAppid());
            tui = true;
        } else if (order.getRealpay().doubleValue() == 0 && order.getGtype() > 2 &&
                (order.getStatus() == 2 || order.getStatus() == 3)) {
            order.setStatus(StatusEnum.cancel.getVal());
            order.updateById();

            OrderGoods og = new OrderGoods();
            og.setStatus(StatusEnum.cancel.getVal());
            og.setOid(order.getId());
            orderGoodsService.update(og, new EntityWrapper<OrderGoods>().eq("oid", order.getId()));
        } else {
            order.updateById();
        }

        if (!tui) {
            json.setMsg("请耐心等待售后处理");
        } else if (map == null || !map.containsKey("result_code") || !map.get("result_code").equals("SUCCESS")) {
            json.setCode(1);
            json.setInfo("钱已退至个人余额账户");
        } else {
            json.setMsg("操作成功");
        }

        return json;
    }

    //取消订单，不退款至用户余额
    @RequestMapping("/api/order/cancel2")
    @ResponseBody
    public Jinfo cancelOrder2(@RequestParam("oid") Long oid, HttpServletRequest req) {
        Jinfo json = new Jinfo();
        logger.debug("------------------------order/cancel2 1111");
        Map<String, Object> map = null;
        if (oid == null) {
            json.setCode(1);
            json.setMsg("请求参数错误");
            return json;
        }
        Order order = orderService.selectById(oid);
        if (order == null) {
            json.setCode(4);
            json.setMsg("该订单不存在");
            return json;
        }
        // 商家秒退
        if (order.getStatus() < 1 || order.getStatus() >= 3) {
            json.setCode(1);
            json.setMsg("当前不支持取消订单操作");
            return json;
        }

        if (Strings.isNullOrEmpty(order.getRefundNo())) {
            order.setRefundNo(StringUtil.getSnNo("R"));
            order.setIsRefund(1);
        } else {
            json.setCode(1);
            json.setMsg("该订单已取消");
            return json;
        }
        logger.debug("------------------------order/cancel2 222");

        // 生成订单取消申请
        OrderRefund orf = refundService.selectOne(new EntityWrapper<OrderRefund>().eq("order_no", order.getOrderNo()));
        if (orf == null) orf = new OrderRefund();

        orf.setRealpay(order.getRealpay());
        orf.setRefund(order.getRealpay());
        orf.setOid(order.getId());
        orf.setOrderNo(order.getOrderNo());
        orf.setRefundNo(order.getRefundNo());
        orf.setRemark("申请取消订单");
        orf.setStatus(1);// 默认受理中
        orf.setState(1);

        String ip = ObjectUtil.getIP();
        orf.setIp(ip);// 默认受理中

        orf.setUid(order.getUid());
        orf.setMid(order.getMid());
        orf.setMpid(order.getMpid());
        orf.setCreatetime(new Date());
        orf.insertOrUpdate();
        logger.debug("------------------------order/cancel2 333");

        MerchantConfig mc = redisService.getMconfig();
        Boolean tui = false;
        if (order.getStatus() == 1) {
            order.setStatus(-1);
            order.updateById();

            OrderGoods og = new OrderGoods();
            og.setStatus(-1);
            og.setOid(order.getId());
            orderGoodsService.update(og, new EntityWrapper<OrderGoods>().eq("oid", order.getId()));
            logger.debug("------------------------order/cancel2 333 aaa");
        } else if (mc.getIsMiaotui() == 1 && order.getRealpay().doubleValue() > 0 &&
                (order.getStatus() == 2 || (order.getStatus() == 3 && order.getGtype() > 1))) {
            // 退款
            map = qnpay.cancelOrderNoaccout(order, ObjectUtil.getAppid());
            if (!map.containsKey("code") || !map.get("code").toString().equals("1")) tui = true;
            logger.debug("------------------------order/cancel2 333 bbb tui=" + tui);
        } else if (order.getRealpay().doubleValue() == 0 && order.getGtype() > 2 &&
                (order.getStatus() == 2 || order.getStatus() == 3)) {
            order.setStatus(-1);
            order.updateById();

            OrderGoods og = new OrderGoods();
            og.setStatus(-1);
            og.setOid(order.getId());
            orderGoodsService.update(og, new EntityWrapper<OrderGoods>().eq("oid", order.getId()));
            logger.debug("------------------------order/cancel2 333 ccc tui=" + tui);

        } else {
            order.updateById();
            logger.debug("------------------------order/cancel2 333 ddd tui=" + tui);
        }
        logger.debug("------------------------order/cancel2 444");

        if (!tui) {
            json.setMsg("请耐心等待售后处理");
        } else if (map == null || !map.containsKey("result_code") || !map.get("result_code").equals("SUCCESS")) {
            json.setCode(1);
            json.setInfo("钱已退至个人余额账户");
        } else {
            json.setMsg("操作成功");
        }

        return json;
    }

    //押金提现申请
    @RequestMapping("/api/order/yjtixiansq")
    @ResponseBody
    public Jinfo yjtixiansq(HttpServletRequest req) {
        Jinfo json = new Jinfo();

        Map<String, Object> map = null;
        Order order = orderService.selectOne(new EntityWrapper<Order>()
                .eq("xftype", XftypeEnum.jyajin.getVal())
                .eq("uid", ObjectUtil.getUid())
                .gt("status", 1)
                .eq("state", 1)
                .lt("is_refund", 1)
        );
        if (order == null) {
            json.setCode(4);
            json.setMsg("暂无押金记录");
            return json;
        }
        if (order.getIsRefund() == 0) {
            json.setCode(1);
            json.setMsg("申请押金提现正在审核中请耐心等待");
            return json;
        }

        order.setRefundNo(StringUtil.getSnNo("R"));
        order.setIsRefund(0);
        order.setRefundtime(new Date());
        order.setModifier(ObjectUtil.getUid());
        order.setModifytime(new Date());
        order.updateById();


        // 生成订单取消申请
        OrderRefund orf = new OrderRefund();
        orf.setRealpay(order.getRealpay());
        orf.setRefund(order.getRealpay());
        orf.setOid(order.getId());
        orf.setOrderNo(order.getOrderNo());
        orf.setRefundNo(order.getRefundNo());
        orf.setRemark("申请押金提现");
        orf.setStatus(1);// 默认受理中
        orf.setState(1);

        String ip = ObjectUtil.getIP();
        orf.setIp(ip);// 默认受理中

        orf.setUid(order.getUid());
        orf.setMid(order.getMid());
        orf.setMpid(order.getMpid());
        orf.setCreatetime(new Date());
        orf.insert();

        return json;
    }

    @RequestMapping("/api/order/delete")
    @ResponseBody
    public JsonDO delOrder(@RequestParam("oid") String oid) {
        JsonDO json = new JsonDO();
        if (Strings.isNullOrEmpty(oid)) {
            json.setCode(1);
            json.setMsg("parameter error");
            return json;
        }
        Order o = orderService.selectById(oid);
        if (o == null) {
            json.setCode(4);
            json.setMsg("order not found");
            return json;
        }
        Long uid = ObjectUtil.getUid();
        Long mid = ObjectUtil.getMid();
        if (uid == null) {
            json.setCode(1);
            json.setMsg("当前用户未登陆");
            return json;
        }
        if (mid == null) {
            json.setCode(1);
            json.setMsg("请求非法");
            return json;
        }
        o.setIsDeleted(1);
        o.updateById();

        OrderGoods og = new OrderGoods();
        og.setOid(o.getId());
        og.setIsDeleted(1);
        orderGoodsService.update(og, new EntityWrapper<OrderGoods>().eq("oid", oid));
        return json;
    }

    @RequestMapping("/api/order/confirm")
    @ResponseBody
    public Jinfo confirmOrder(@RequestParam("orderNo") String orderNo) {
        Jinfo json = new Jinfo();
        if (Strings.isNullOrEmpty(orderNo)) {
            json.setCode(1);
            json.setMsg("parameter error");
            return json;
        }
        Order order = orderService.selectOne(new EntityWrapper<Order>().eq("order_no", orderNo));
        // 客户点击确认收货，入账通知
        MerchantConfig mconfig = redisService.getMconfig(order.getMpid());
        if (mconfig.getShowCommet() != null && mconfig.getShowCommet() == 1) {
            qnpay.updateOrderStatus(order, StatusEnum.commenting.getVal());
        } else {
            qnpay.updateOrderStatus(order, StatusEnum.finish.getVal());
        }

        AkkaServer.system.actorOf(Props.create(OrderActor.class))
                .tell(Constants.AKKA_MSG_FAN_RUZHANG + "@" + order.getOrderNo() + "@" + mconfig.getFantimeType(), ActorRef.noSender());
        return json;
    }

    @RequestMapping("/api/sorder/confirm")
    @ResponseBody
    public Jinfo sconfirmOrder(@RequestParam("orderNo") String orderNo) {
        Jinfo json = new Jinfo();
        if (Strings.isNullOrEmpty(orderNo)) {
            json.setCode(1);
            json.setMsg("parameter error");
            return json;
        }
        Order order = orderService.selectOne(new EntityWrapper<Order>().eq("order_no", orderNo));
        // 客户点击确认收货，入账通知
        Store store = redisService.getStore(order.getSid());

        //暂时不支持评论
//        if (mconfig.getShowCommet() != null && mconfig.getShowCommet() == 1) {
//            qnpay.updateOrderStatus(order, StatusEnum.commenting.getVal());
//        } else {
        qnpay.updateOrderStatus(order, StatusEnum.finish.getVal());
//        }

        //核销领取货之后处理自购返奖励
        //发货15天后处理自购返奖励
        //===待完善===
        AkkaServer.system.actorOf(Props.create(OrderActor.class))
                .tell(Constants.AKKA_MSG_ORDER_ZIGOUFAN + "@" + order.getId() + "@" + FantimeType.confirm.getVal(), ActorRef.noSender());

        //===商家入账处理
        if (order.getSid() != null && order.getSid().longValue() > 0) {
            AkkaServer.system.actorOf(Props.create(OrderActor.class))
                    .tell(Constants.AKKA_MSG_ORDER_STORE_PAY + "@" + order.getId(), ActorRef.noSender());
        }

        //===盟主入账处理
        if (order.getLmfan() != null && order.getLmfan().doubleValue() > 0 &&
                order.getSid() != null && order.getSid().longValue() > 0) {
            AkkaServer.system.actorOf(Props.create(OrderActor.class))
                    .tell(Constants.AKKA_MSG_ORDER_MENGZHU_PAY + "@" + order.getId(), ActorRef.noSender());
        }

        //===平台入账处理
        if (order.getPtfan() != null && order.getPtfan().doubleValue() > 0 &&
                order.getSid() != null && order.getSid().longValue() > 0) {
            AkkaServer.system.actorOf(Props.create(OrderActor.class))
                    .tell(Constants.AKKA_MSG_ORDER_PLATFORM_PAY + "@" + order.getId(), ActorRef.noSender());
        }

        //领取货之后分销结算，触发时机：扫码核销确认收货【点击确认收货】
        //商品分享直推奖励
        logger.info("---------------------------------------------------hxok order.getSharefan()=" + order.getSharefan());
        logger.info("---------------------------------------------------hxok order.getFantimeType()=" + order.getFantimeType());
        if (order.getSharefan() != null && order.getSharefan().doubleValue() > 0
                && order.getFantimeType() == FantimeType.confirm.getVal()) {
            AkkaServer.system.actorOf(Props.create(OrderActor.class))
                    .tell(Constants.AKKA_MSG_ORDER_SHAREFAN + "@" + order.getId(), ActorRef.noSender());
        }

        return json;
    }

    @RequestMapping("/api/order/detail")
    @ResponseBody
    public Jinfo getOrderDetailById(@RequestParam("oid") long oid,
                                    HttpServletRequest req
    ) {
        Jinfo jinfo = new Jinfo();
        Order order = orderService.selectById(oid);
        if (order == null) {
            jinfo.setCode(4);
            return jinfo;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        List<OrderGoods> goods = orderGoodsService.selectList(
                new EntityWrapper<OrderGoods>().eq("oid", order.getId()).orderBy("is_default"));

        map.clear();
        map.put("orderInfo", order);
        map.put("goods", goods);

        if (order.getIsNeedLogistics() == 1) {
//            map.put("traces",goodscategory);// 物流跟踪
        } else {
            map.put("traces", false);
        }
        jinfo.setInfo(map);
        return jinfo;
    }

    @RequestMapping("/api/bookorder/detail")
    @ResponseBody
    public Jinfo getBookOrderDetailById(@RequestParam("oid") long oid,
                                        @RequestParam(value = "isDuihuan", required = false) Integer isDuihuan,
                                        @RequestParam(value = "dhtype", required = false) Integer dhtype,
                                        HttpServletRequest req) {
        Jinfo json = new Jinfo();
        Order order = orderService.selectById(oid);
        Map<String, Object> map = new HashMap<String, Object>();
        Goods goods = goodsService.selectById(order.getGid());

        OrderExt orderExt = orderExtService.selectOne(new EntityWrapper<OrderExt>()
                .eq("gid", order.getGid())
                .eq("oid", order.getId()));

        map.clear();
        map.put("order", order);
        map.put("goods", goods);
        map.put("orderExt", orderExt);

        json.setInfo(map);
        return json;
    }

    @RequestMapping("/api/reserving/add")
    @ResponseBody
    public Jinfo addReservingOrder(Order order, OrderGoods OrderGoods,
                                   @RequestParam(value = "isDuihuan", required = false) Integer isDuihuan,
                                   @RequestParam(value = "dhtype", required = false) Integer dhtype,
                                   @RequestParam(value = "tmplIds", required = false) String tmplIds,
                                   @RequestParam(value = "addrid", required = false) Long addrid,
                                   HttpServletRequest req) {

        Jinfo json = new Jinfo();
        BigDecimal prices = new BigDecimal(req.getParameter("price"));//商品总价格
        BigDecimal yunfei = new BigDecimal(0);//运费
        String reservingTimeStr = req.getParameter("reservingTimeStr") == null ? null : req.getParameter("reservingTimeStr").toString();//总价
        String yytime = req.getParameter("yytime") == null ? null : req.getParameter("yytime").toString();//总价
//        order.setReservingTime(DateUtil.toDate(reservingTimeStr));
        order.setYytime(yytime != null ? yytime : reservingTimeStr);

        logger.info(">>>amountGoods=" + prices);
        logger.info(">>>amountYunfei=" + yunfei);
        logger.info(">>>amountTotle=" + prices);

        logger.info(">>>>>>>>>>>>>>>order=" + order);
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>orderExt=" + OrderGoods);

        // 生成订单
        String uid = ObjectUtil.getUid().toString();
        order.setState(1);
        order.setUid(Long.parseLong(uid));
        order.setMid(ObjectUtil.getMid());
        order.setMpid(ObjectUtil.getMpid());

        order.setOrderNo(StringUtil.getSnNo("Y"));// 预约订单
        order.setShortno(orderService.getShortno(ObjectUtil.getMpid()));
        order.setServiceCode(StringUtil.getServiceCode());

        order.setStatus(1);
        order.setExpire(30);

        if (order.getRealpay().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.weixin.getVal());

        } else if (order.getDeduction().doubleValue() > 0) {
            order.setPayType(PaytypeEnum.deduction.getVal());
        } else {
            order.setPayType(PaytypeEnum.daofu.getVal());
        }
        order.setYunfei(new BigDecimal(0));
        order.setTotal(order.getPrices());
        order.setXftype(XftypeEnum.buy.getVal());
        order.setType(YXType.common.getVal());

        BigDecimal num = new BigDecimal(order.getGoodsNumber());
        BigDecimal zero = new BigDecimal(0);
        //自购返
        BigDecimal fanjifen = new BigDecimal(0);//返积分
        BigDecimal fanqian = fanjifen;//代金券|现金
        BigDecimal fanbi = fanjifen;//返币

        Goods goods = goodsService.selectById(order.getGid());
        if (goods != null && goods.getZgfanType() != null && goods.getZgfanType() > 0) {
            BigDecimal zgfanMount = new BigDecimal(goods.getZgfanMount());
            if (goods.getZgfanType() == XffanType.jifen.getVal()) fanjifen = zgfanMount.multiply(num);
            if (goods.getZgfanType() == XffanType.qian.getVal()) fanqian = zgfanMount.multiply(num);
            if (goods.getZgfanType() == XffanType.xnbi.getVal()) fanbi = zgfanMount.multiply(num);

            order.setFantimeType(goods.getFantimeType());
            order.setShareBonusType(goods.getShareBonusType());//分销返利类型
            order.setSharefan(goods.getShareMount());//分销返利类型

            order.setFanjifen(fanjifen);
            order.setFanbi(fanbi);
            order.setFanqian(fanqian);

        }

        order.setOrderType(0);
        order.setIsComment(0);

        if (order.getRealpay().doubleValue() > 0) {
            order.setStatus(1);
            order.setFhstate(1);//预约类=虚拟商品,不需要发货
        } else {
            order.setStatus(3);
            order.setFhstate(1);//预约类=虚拟商品,不需要发货
        }

        order.setCreatetime(new Date());
        BigDecimal discount = new BigDecimal(0);//运费
        if (order.getActivityDiscount() != null) {
            discount = discount.add(order.getActivityDiscount());
        }
        if (order.getCouponDiscount() != null) {
            discount = discount.add(order.getCouponDiscount());
        }
        if (order.getJifenDiscount() != null) {
            discount = discount.add(order.getJifenDiscount());
        }
        if (order.getMemberDiscount() != null) {
            discount = discount.add(order.getMemberDiscount());
        }
        order.setDiscount(discount);
        order.setFantimeType(redisService.getMconfig().getFantimeType());
        if (order.getSid() != null) {
            Store store = redisService.getStore(order.getSid());
            if (store != null) {
                order.setSname(store.getName());
            }
        }

        logger.debug(">>>order=" + JSON.toJSONString(order));

        if (order.getId() == null || order.getId() == 0) {
            order.setId(null);
            order.setCreatetime(new Date());
            order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
            order.insert();
        } else {
            order.setModifytime(new Date());
            order.updateById();
        }
        if (!Strings.isNullOrEmpty(tmplIds)) {
            AkkaServer.system.actorOf(Props.create(TemplatemsgActor.class))
                    .tell("AddTplform@" + order.getId() + "@" + tmplIds, ActorRef.noSender());
        }

        if (order.getStatus() == 3) {
            processPayAccoumt(order, isDuihuan, dhtype);
        }
        logger.info("========order =" + JSON.toJSONString(order));
//        logger.info("========orderExt =" + JSON.toJSONString(orderExt));
        Boolean flag = true;
        if (order.getRealpay().doubleValue() > 0) {
            Map<String, Object> map = orderService.getPaymap(order, false, "在线预约支付");
            json.setInfo(map);
            logger.info("========================order map=" + JSON.toJSONString(map));
        } else {
            json.setInfo(order);
            //短信提醒
            AkkaServer.system.actorOf(Props.create(SmsActor.class))
                    .tell(Constants.AKKA_MSG_SMS_YUYUE + "@" + order.getUid() + "@" + order.getId(), ActorRef.noSender());
            //预约奖励
            AkkaServer.system.actorOf(Props.create(FanActor.class))
                    .tell(Constants.AKKA_MSG_YUYUE + "@" + order.getUid() + "@" + order.getMpid() + "@" + order.getId(), ActorRef.noSender());
        }
        logger.info("========================order flag=" + flag);

        return json;
    }

    //处理支付成功的订单
    //本逻辑处理未实际支付现金逻辑（realpay==0）
    //处理实付金额为零的情况
    private void processPayAccoumt(Order order, Integer isDuihuan, Integer dhtype) {
        logger.info("========================processPayAccoumt=" + JSON.toJSONString(order));

        if (order == null) return;
        boolean updateflag = false;
        boolean flag = false;
        BigDecimal zero = new BigDecimal(0);
        Long gid = order.getGid();
        Goods goods = goodsService.selectById(gid);
        if (gid != null && goods != null) {
            Goods ngoods = new Goods();
            ngoods.setId(order.getGid());
            ngoods.setCanyushu(goods.getCanyushu() == null ? 1 : goods.getCanyushu() + 1);

            ngoods.setNumberSale(goods.getNumberSale() == null ? order.getGoodsNumber() : order.getGoodsNumber() + goods.getNumberSale());
            if (goods.getStores() != null) ngoods.setStores(goods.getStores() - order.getGoodsNumber());

            ngoods.setNumberOrders(goods.getNumberOrders() + 1);
            logger.debug("=============================before ngoods.updateById() ngoods=" + JSON.toJSONString(ngoods));
            ngoods.updateById();
        }

        long uid = order.getUid();
        long mid = order.getMid();
        long mpid = order.getMpid();

        // 更新优惠券信息
        if (order.getCouponId() != null && order.getCouponId() > 0) {
            Coupon coupon = new Coupon();
            coupon.setId(order.getCouponId());
            coupon.setIsUsed(1);
            coupon.setIsUnused(0);
            coupon.setUsetime(new Date());
            coupon.setCost(order.getCouponDiscount());
            coupon.setSn(order.getOrderNo());
            coupon.setModifier(uid);
            coupon.setMid(mid);
            coupon.setModifytime(new Date());

            updateflag = coupon.insertOrUpdate();
            logger.debug(">>>at coupon updateflag=" + updateflag);
        }

        // 更新积分信息
        updateflag = false;
        int add = 0;
        JifenFlow jf = null;
        if (order.getJifen() != null && order.getJifen().doubleValue() > 0) {
            // 使用积分后，本次购买商品不再赠送积分
            jf = new JifenFlow();

            // *******  客户消耗  *******
            jf.setNum(order.getJifen());
            jf.setSn(order.getOrderNo());// 抵扣积分时 = 订单号
            jf.setIotype(IotypeEnum.output.getVal());//积分消费
            jf.setJftype(JftypeEnum.duihuan.getVal());//积分消费
            jf.setCreatetime(new Date());
            jf.setUid(uid);
            jf.setMid(mid);
            jf.setMpid(mpid);
            jf.setRemark("消费抵扣积分");
            jf.setSn(order.getOrderNo());
            jf.setIsConfirm(1);
            jf.setConfirmDate(new Date());
            jf.setState(1);
            updateflag = jf.insert();
            logger.debug(">>> JifenFlow insert=" + updateflag);

            add = -1;
            // 支付完成更新总积分
        }

        if (add != 0) {
            flag = false;
            while (!flag) {
                Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", uid));
                long v = jifen.getVersion();
                jifen.setTotal(add == 1 ? jifen.getTotal().add(jf.getNum()) : jifen.getTotal().subtract(jf.getNum()));
                jifen.setVersion(jifen.getVersion() + 1);
                jifen.setModifytime(new Date());
                jifen.setModifier(uid);
                flag = jifenService.update(jifen, new EntityWrapper<Jifen>().eq("version", v).eq("uid", uid));
                logger.debug(">>>at jifenService update=" + flag);
            }
        }

        flag = false;
        // 更新会员账户余额信息 = 账户 + 流水
        // 使用会员现金余额
        User user = userService.selectById(uid);

        BigDecimal ambc = zero;
        BigDecimal mkbc = zero;
        Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));

        if (act == null) {
            act = accountService.initAccount(user.getId(), user.getMid(), user.getMpid());
        }

        Maccount maccount = maccountService.selectOne(new EntityWrapper<Maccount>().eq("mid", mid));
        if (maccount == null) maccount = orderService.initMaccount();

        if (isDuihuan == null) {
            if (act.getAmount().doubleValue() >= order.getDeduction().doubleValue()) {
                ambc = order.getDeduction();
            } else if (act.getAmount().doubleValue() <= 0) {
                mkbc = order.getDeduction();
            } else {
                ambc = act.getAmount();
                mkbc = order.getDeduction().subtract(act.getAmount());
            }

            if (order.getDeduction() != null && order.getDeduction().doubleValue() > 0) {

                AccountFlow af = new AccountFlow();

                af.setRealpay(zero);
                af.setAmount(ambc);
                af.setDikou(mkbc);
                af.setTotal(af.getRealpay().add(af.getAmount()).add(af.getDikou()));

                af.setSn(order.getOrderNo());
                af.setTransactionid(order.getTransactionId());
                af.setIotype(IotypeEnum.output.getVal());
                af.setXftype(XftypeEnum.buy.getVal());

                af.setNickname(user != null ? user.getNickName() : null);
                af.setHeadimg(user != null ? user.getAvatarPic() : null);
                af.setPhone(user != null ? user.getPhone() : null);
                af.setIsConfirm(-1);
                af.setState(1);

                af.setTradetime(new Date());
                af.setCreatetime(af.getTradetime());
                af.setRemark("使用会员余额进行消费");
                af.setUid(uid);
                af.setMid(mid);
                af.setMpid(mpid);
                af.setMpid(order.getMpid());
//                af.insert();
                accountService.addAccountOutFlow(af);
            }

            ambc = zero;
            mkbc = zero;

            // 只要未实际在线支付金额，商家销售金额+可用金额无变化
            if (order.getDeduction().doubleValue() > 0) {
                if (act.getAmount().doubleValue() >= order.getDeduction().doubleValue()) {
                } else if (act.getAmount().doubleValue() <= 0) {
                    mkbc = order.getDeduction();
                } else {
                    mkbc = order.getDeduction().subtract(act.getAmount());
                }
            }
            ambc = ambc.add(order.getRealpay());// 实际支付现金为0
            BigDecimal sale = order.getRealpay();//实际支付现金为0
            mkbc = mkbc.add(order.getDiscount());

            MaccountFlow maf = new MaccountFlow();
            maf.setAmount(ambc);
            maf.setMamount(mkbc);

            maf.setSn(order.getOrderNo());
            maf.setTransactionid(order.getTransactionId());
            maf.setJifen(order.getJifen());
            maf.setIotype(IotypeEnum.input.getVal());
            maf.setXftype(XftypeEnum.sell.getVal());

            maf.setIsConfirm(-1);
            maf.setCreatetime(new Date());
            maf.setTradetime(new Date());

            maf.setState(1);
            maf.setMid(mid);
            maf.setUid(uid);
            maf.setMpid(order.getMpid());
            updateflag = maf.insert();
            logger.debug(">>>at maccountFlow updateflag=" + updateflag);

            flag = false;
            if (updateflag == true) {

                logger.debug("========maccount=" + JSON.toJSONString(maccount));
                Maccount acc = new Maccount();//realpay=0支付成功
                while (!flag) {
                    acc.setAmount(maccount.getAmount().add(ambc));
                    acc.setTotal(maccount.getTotal().add(ambc));
                    acc.setMamount(maccount.getMamount().add(mkbc));
                    acc.setVersion(maccount.getVersion() + 1);

                    if (maccount.getJifen() == null) maccount.setJifen(new BigDecimal(0));
                    if (order.getJifen() != null && order.getJifen().doubleValue() > 0)
                        acc.setJifen(maccount.getJifen().add(order.getJifen()));

                    updateflag = maccountService.update(acc, new EntityWrapper<Maccount>().eq("version", maccount.getVersion()));
                    logger.debug(">>>at maccountService updateflag=" + updateflag);
                    flag = updateflag;

                    maf.setIsConfirm(1);
                    maf.setLasttotal(maccount.getTotal());
                    maf.setConfirmDate(new Date());

                    if (!flag) maccount = maccountService.selectOne(new EntityWrapper<Maccount>().eq("mid", mid));
                    else maf.insertOrUpdate();
                }
            }
        }

        if (isDuihuan != null && isDuihuan.intValue() == 1) {
            //发送模板消息
//            Templatemsg templatemsg = templatemsgService.selectOne(new EntityWrapper<Templatemsg>()
//                    .eq("tplcode", "payok")
//                    .eq("mpid", order.getMpid())
//                    .orderBy("id"));
//
//            Tplform tplform = tplformService.selectOne(new EntityWrapper<Tplform>()
//                    .eq("state", 1)
//                    .eq("uid", user.getId())
//                    .orderBy("id"));
//
//            if (tplform != null) {
//                List<TemplateData> tpllist = new ArrayList<TemplateData>();
//
//                tpllist.add(new TemplateData("keyword1", order.getGoodsName()));
//                tpllist.add(new TemplateData("keyword2", DateUtil.toDateString(order.getCreatetime(), "yyyy-MM-dd hh:mm:ss")));
//                tpllist.add(new TemplateData("keyword3", order.getRealpay().toString() + "积分"));
//                tpllist.add(new TemplateData("keyword4", order.getPhone()));
//                tpllist.add(new TemplateData("keyword5", order.getAddress()));
//
//                WxmappTemplate wxtpl = new WxmappTemplate();
//                wxtpl.setToUser(tplform.getOpenid());
//                wxtpl.setForm_id(tplform.getFormid());
//
//                wxtpl.setTemplateId(templatemsg.getTplid());
//                String pageparam = mconfig.getShowForpay() == 1 ? "1" : "2";
//                wxtpl.setPage(templatemsg.getPage() + pageparam);
//                wxtpl.setTemplateDataList(tpllist);
//
//                ObjectUtil.sendTemplateMsg(redisService.getWxtoken(tplform.getMpid().toString()), wxtpl);
//
//                tplform.setState(-1);
//                tplform.setModifytime(new Date());
//                tplform.updateById();
//                logger.debug("======orderNotify send tplmsg ok for user phone=" + user.getPhone());

            //==========发送模板消息OVER============
        }

        MerchantApp mapp = redisService.getMApp();

        logger.info("----------------------maccount=" + JSON.toJSONString(maccount));
        logger.info("----------------------mapp=" + JSON.toJSONString(mapp));
        // 默认只给客服1发订单短信提醒
        if (!Strings.isNullOrEmpty(mapp.getKefu1())) {
            MconfigExt mconfigExt = mconfigExtService.selectById(mapp.getId());
//            String sms = "【恰恰全】发货通知：用户"+order.getLinkman()+"手机号"+order.getPhone()+"已下单购买"+order.getGoodsName()+"等，请尽快"+(order.getGtype()>=3?"上门服务":"发货");
            String sms = String.format("发货通知：小程序用户%s(%s)已下单购买%s等，请尽快发货", order.getLinkman(), order.getPhone(), order.getGoodsName());
            String[] params = {order.getLinkman(), order.getPhone(), order.getGoodsName()};
            if (maccount.getSmstotal() != null && maccount.getSmstotal() > 0 && mconfigExt != null && mconfigExt.getSmstplid() != null) {
//                smslogService.sendOnesms(mapp.getKefu1(),sms);
                smslogService.sendOnetplsmsjf(mapp.getKefu1(), sms, params, mconfigExt.getSmstplid(), mid, mpid);
            }
        }

        if (dhtype != null && dhtype.intValue() == XffanType.jifen.getVal()) {

//            jifenService.addJifenFlow(adminuser.getId(), ObjectUtil.getMid(), ObjectUtil.getMpid(),
//                    order.getJifen(), true, FantimeType.now.getVal(),
//                    StringUtil.getSnNo("JF"), IotypeEnum.input, JftypeEnum.sell, "", 0l);
            logger.info("------------------------maccountService.addMamountFlow start");
            maccountService.addMamountFlow(ObjectUtil.getMid(), zero, zero,
                    true, order.getJifen(), order.getOrderNo(), IotypeEnum.input, XftypeEnum.sell.getVal(), "用户积分兑换收款", 0l, "0");

            // 兑换佣金返利
            // 返利推荐人【适用于恰恰全积分兑换平台】
            AkkaServer.system.actorOf(Props.create(FanliActor.class))
                    .tell(Constants.AKKA_FX_HEXIAO_OK + "@" + ObjectUtil.getUid() + "@" + order.getJifen() + "@" + XffanType.jifen.getVal(), ActorRef.noSender());

        }
        if (dhtype != null && dhtype.intValue() == XffanType.xnbi.getVal()) {
            //===待完善，订单支付暂未支持虚拟币支付
//            xnbiService.addXnbiFlow(adminuser.getId(), ObjectUtil.getMid(), ObjectUtil.getMpid(),
//                    order.getJifen(), true, FantimeType.now.getVal(),
//                    StringUtil.getSnNo("BI"), IotypeEnum.input, JftypeEnum.sell, "", 0l);
        }

        //处理自购返利+推荐返利
        AkkaServer.system.actorOf(Props.create(FanliActor.class))
                .tell(Constants.AKKA_FX_ORDER_PAY_OK + "@" + ObjectUtil.getUid() + "@" + order.getId() + "@0", ActorRef.noSender());

    }

    @RequestMapping("/api/order/book/update")
    @ResponseBody
    public Jinfo bookOrderUpdate(Order order,
                                 @RequestParam(value = "isDuihuan", required = false) Integer isDuihuan,
                                 @RequestParam(value = "dhtype", required = false) Integer dhtype,
                                 HttpServletRequest req) {

        Jinfo json = new Jinfo();
        order.setModifytime(new Date());
        order.updateById();

        order = orderService.selectById(order.getId());
        processPayAccoumt(order, isDuihuan, dhtype);

        return json;
    }

    //手机商户端配送发货接口
    //oid:订单号
    //pstype:配送方式
    //shipperName:快递公司
    //shipperCode:快递公司编码
    //yundanno:运单号
    @RequestMapping("/api/order/peisong")
    @ResponseBody
    public Jinfo peisong(@RequestParam("oid") long oid,
                         @RequestParam(value = "pstype", required = false) Integer pstype,
                         @RequestParam(value = "shipperName", required = false) String shipperName,
                         @RequestParam(value = "shipperCode", required = false) String shipperCode,
                         @RequestParam(value = "yundanno", required = false) String yundanno
    ) {
        Jinfo jinfo = new Jinfo();
        Order order = orderService.selectById(oid);
        if (order == null) {
            jinfo.setCode(4);
            return jinfo;
        }
        Order norder = new Order();
        norder.setId(oid);
        User user = redisService.getUser();

        if (pstype != null && pstype == 1) {
            // 第三方快递配送
            norder.setShipperName(shipperName);
            norder.setShipperCode(shipperCode);
            norder.setYundanno(yundanno);
            norder.setIsNeedLogistics(1);
            norder.setFhstate(2);//发完货之后待确认，送货到地点第三方来触发【送到地点】动作，(本系统暂时无法触发2)
        } else if (pstype != null && pstype == 2) {
            // ====外卖配送
            norder.setShipperName(shipperName);
            norder.setShipperCode(shipperCode);
            norder.setFhstate(2);//发完货之后待确认，送货到地点第三方来触发【送到地点】动作，(本系统暂时无法触发2)
        } else if (pstype == 3) {
            norder.setShipperCode(user.getPhone());//商家自行配送，谁配送留睡的电话
            norder.setShipperName("商家配送");
            norder.setFhstate(1);//发完货之后待确认，送到地方后自行触发【配送完成】2动作
        } else if (pstype == 4) {
            //用户自提货，到店自取
            norder.setShipperName("用户自提");
            norder.setFhstate(1);//备货配货完成1+【到店核销动作触发2||到店服务完成后触发2】
        }

        norder.setShipperMethod(pstype);
        norder.setStatus(StatusEnum.receving.getVal());
        norder.setModifier(ObjectUtil.getUid());
        norder.setModifytime(new Date());
        norder.updateById();


        OrderGoods norderGoods = new OrderGoods();
        norderGoods.setId(oid);
        norderGoods.setStatus(norder.getStatus());
        norderGoods.setFhstate(norder.getStatus());
        norderGoods.setShipperCode(norder.getShipperCode());
        norderGoods.setShipperName(norder.getShipperName());

        norderGoods.setModifier(ObjectUtil.getUid());
        norderGoods.setModifytime(new Date());

        orderGoodsService.update(norderGoods, new EntityWrapper<OrderGoods>().eq("oid", oid));

        //领取货之后分销结算，触发时机：扫码核销确认收货【+点击确认收货】
        //商品分享直推奖励，确认收货||扫码核销时||订单确认周期到期触发
        // ===【平台入驻商家】入账处理，确认收货||扫码核销时||订单确认周期到期触发
        // 领取货之后返自购奖励，确认收货||扫码核销时||订单确认周期到期触发

        return jinfo;
    }

    //配送完成，改变配送状态
    //区分实物订单和服务订单
    @RequestMapping("/api/order/psover")
    @ResponseBody
    public Jinfo psover(@RequestParam("oid") long oid) {
        Jinfo jinfo = new Jinfo();
        Order order = orderService.selectById(oid);
        if (order == null) {
            jinfo.setCode(4);
            return jinfo;
        }
        MerchantConfig mconfig = redisService.getMconfig();
        Order norder = new Order();
        norder.setId(oid);
        norder.setFhstate(2);//1:配送中；2：配送完成
        if (order.getGtype() == 3)
            norder.setStatus(mconfig.getShowCommet() != null && mconfig.getShowCommet() == 1 ? StatusEnum.commenting.getVal() : StatusEnum.finish.getVal());

        norder.setModifier(ObjectUtil.getUid());
        norder.setModifytime(new Date());

        norder.updateById();

        OrderGoods norderGoods = new OrderGoods();
        norderGoods.setId(oid);
        norderGoods.setFhstate(2);//1:配送中；2：配送完成
        if (order.getGtype() == 3)
            norder.setStatus(mconfig.getShowCommet() != null && mconfig.getShowCommet() == 1 ? StatusEnum.commenting.getVal() : StatusEnum.finish.getVal());
        norderGoods.setModifier(ObjectUtil.getUid());
        norderGoods.setModifytime(new Date());

        orderGoodsService.update(norderGoods, new EntityWrapper<OrderGoods>().eq("oid", oid));

        return jinfo;
    }


    /*
     * 我的所有订单
     * 普通商品订单+活动订单(非买单订单)
     */
    @RequestMapping("/api/order/unilist")
    @ResponseBody
    public Jinfo unilist(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                         @RequestParam(value = "pageSize", required = false) int pageSize,
                         @RequestParam(value = "status", required = false) int status,
                         @RequestParam(value = "fhstate", required = false) Integer fhstate,
                         @RequestParam(value = "isadmin", required = false) Integer isadmin,
                         @RequestParam(value = "tuihuan", required = false) Integer tuihuan,
                         HttpServletRequest req) {
        Jinfo jinfo = new Jinfo();
        Map<String, Object> map = new HashMap<String, Object>();
        Long mpid = ObjectUtil.getMpid();
        if (ObjectUtil.getUid() == null) {
            jinfo.setCode(1);
            jinfo.setMsg("请授权登录后再查看");
            return jinfo;
        }
        String uid = ObjectUtil.getUid().toString();
        Page<Order> page = new Page<Order>(pageIndex, pageSize);

        Wrapper<Order> entity = new EntityWrapper<Order>()
                .setSqlSelect("id,status,pic,gid,sid,sname,type,gtype,realpay,price,saleprice,total,yunfei,remark,createtime,endtime," +
                        "service_code serviceCode,deduction,goods_name goodsName,fhstate,shipper_method shipperMethod,goods_number goodsNumber," +
                        "yundanno,refund_no refundNo,is_refund isRefund,order_no orderNo,order_type orderType,total,is_comment isComment")
                .eq("mpid", mpid)
                .eq("state", 1)
                .ge("gtype", 1)
                .eq("is_deleted", -1);
//                .eq("type", 0)
//                .eq("is_deleted", 0).le("gtype", 2);
        if (isadmin == null) entity.eq("uid", uid);
        if (status == 3) {
//            if (fhstate != null && fhstate == 1) entity.eq("status", status).eq("fhstate", fhstate);
//            else if (fhstate != null && fhstate == 2) entity.eq("fhstate", fhstate);
//            else if (fhstate == null) entity.eq("status", status);
            entity.ge("status", 2);
            entity.le("status", 3);
        } else if (status == 99) {
        } else {
            entity.eq("status", status);
        }
        if (tuihuan != null && tuihuan == 1) {
            entity.eq("is_refund", 1);
        } else {
            entity.ne("is_refund", 1);
        }

        entity.orderBy("id", false);
        Page<Order> plist = orderService.selectPage(page, entity);
        if (plist == null || plist.getSize() == 0) {
            jinfo.setInfo(new ArrayList());
            return jinfo;
        }

        List<Order> orders = plist.getRecords();
        Date now = new Date();

        for (Order o : orders) {
            map.clear();
            map.put("oid", o.getId());
            o.setList(orderGoodsService.selectByMap(map));
            if (o.getIsRefund() == 1)
                o.setOrderRefund(refundService.selectOne(new EntityWrapper<OrderRefund>()
                        .setSqlSelect("id,realpay,refund,order_no orderNo,refund_no refundNo,status")
                        .eq("oid", o.getId())));

            //抽奖
            if (o.getType() == YXType.choujiang.getVal()) {
                o.setJps(choujiangLogService.selectList(new EntityWrapper<ChoujiangLog>()
                        .setSqlSelect("id,name,pic,level")
                        .eq("oid", o.getId()).eq("is_zhong", 1)));
            }

            //计算倒计时
            if (o.getEndtime() != null && now.getTime() < o.getEndtime().getTime()) {
                o.setTimeleft(DateUtil.getDatePoor(o.getEndtime(), now));
            }
        }

        jinfo.setInfo(orders);
        return jinfo;
    }

    //查询门店商家交易记录
    @RequestMapping("/api/order/jylist")
    @ResponseBody
    public Jinfo jylist(@RequestParam(value = "sid", required = false) Long sid,
                        @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                        @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Jinfo json = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;

        Page page2 = new Page(pageIndex, pageSize);
        Wrapper entity = new EntityWrapper<Order>()
                .setSqlSelect("linkman,phone,createtime,goods_number goodsNumber")
                .gt("status", 1).eq("state", 1)
                .eq("mpid", ObjectUtil.getMpid())
                .orderBy("id", false);
        if (sid != null) entity.eq("sid", sid);

        Page<Order> jyorders = orderService.selectPage(page2, entity);

        List<Order> jylist = jyorders.getRecords();
        for (Order item : jylist) {
            item.setPhone(goodsService.replaceXing(item.getPhone()));
            item.setLinkman(goodsService.replaceMiddle(item.getLinkman()));
            item.setRemark(DateUtil.toDateString(item.getCreatetime(), "MM-dd hh:mm:ss"));
        }
        json.setInfo(jylist);
        return json;
    }


    /*
     * 平台版商户订单，实物商城商品
     * 普通商品订单，非活动订单
     */
    @RequestMapping("/api/order/hkymchlist")
    @ResponseBody
    public Jinfo hkymchlist(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                            @RequestParam(value = "pageSize", required = false) int pageSize,
                            @RequestParam(value = "status", required = false) int status,
                            @RequestParam(value = "sid", required = false) Long sid,
                            @RequestParam(value = "fhstate", required = false) Integer fhstate,
                            @RequestParam(value = "tuihuan", required = false) Integer tuihuan) {
        Jinfo jinfo = new Jinfo();
        Map<String, Object> map = new HashMap<String, Object>();
        Long mpid = ObjectUtil.getMpid();
        MerchantConfig mconfig = redisService.getMconfig(mpid);
        Page<Order> page = new Page<Order>(pageIndex, pageSize);
        if (sid == null) sid = ObjectUtil.getSid();
        if (sid == null) {
            jinfo.setCode(1);
            jinfo.setMsg("参数有误");
            return jinfo;
        }

        Wrapper<Order> entity = new EntityWrapper<Order>()
                .eq("mpid", mpid)
                .eq("state", 1)
                .ge("gtype", 1)
                .eq("type", 0)
                .eq("sid", sid)
                .eq("xftype", XftypeEnum.buy.getVal())
                .ne("status", StatusEnum.cancel.getVal())
                .eq("is_deleted", -1);

        Store store = redisService.getStore(sid);

        if (store.getShowforpay() == null || store.getShowforpay() != 1) {
            entity.ne("status", StatusEnum.forpay.getVal());
        }

        if (status == 3) {
            entity.eq("status", status).eq("fhstate", fhstate);
        } else if (status == 99) {
        } else {
            entity.eq("status", status);
        }

        if (tuihuan != null && tuihuan == 1) {
            entity.eq("is_refund", 1);
        } else {
            entity.ne("is_refund", 1);
        }

        entity.orderBy("id", false);
        Page<Order> plist = orderService.selectPage(page, entity);
        if (plist == null || plist.getSize() == 0) {
            jinfo.setInfo(new ArrayList());
            return jinfo;
        }

        List<Order> orders = plist.getRecords();

        for (Order o : orders) {
            map.clear();
            map.put("oid", o.getId());
            o.setList(orderGoodsService.selectByMap(map));
            if (o.getIsRefund() == 1)
                o.setOrderRefund(refundService.selectOne(new EntityWrapper<OrderRefund>()
                        .setSqlSelect("id,realpay,refund,order_no orderNo,refund_no refundNo,status")
                        .eq("oid", o.getId())));
        }

        jinfo.setInfo(orders);
        return jinfo;
    }

    /*
     * 平台版商户员工业绩订单
     * 员工推荐转发购买生成的订单
     * 只统计活动订单
     * datetype 统计日期类型@1：今日 2：昨日 3：本月
     */
    @RequestMapping("/api/order/mchyjlist")
    @ResponseBody
    public Jinfo mchyjlist(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                           @RequestParam(value = "pageSize", required = false) int pageSize,
                           @RequestParam(value = "datetype", required = false) int datetype) {
        Jinfo jinfo = new Jinfo();
        Map<String, Object> map = new HashMap<String, Object>();
        Long mpid = ObjectUtil.getMpid();

        Page<Order> page = new Page<Order>(pageIndex, pageSize);
        Long uid = ObjectUtil.getUid();
        Wrapper<Order> entity = new EntityWrapper<Order>()
                .eq("mpid", mpid)
                .eq("state", 1)
                .ge("gtype", 1)
                .ge("type", 1)
                .eq("fanuid", uid)
                .eq("xftype", XftypeEnum.buy.getVal())
                .eq("is_deleted", -1);

        entity.ge("status", 1).ne("is_refund", 1);
        String startday1 = "";
        String endday1 = "";

        String startday2 = "";
        String endday2 = "";

        String startday3 = "";
        String endday3 = "";

        Date today = new Date();
        Calendar cal = Calendar.getInstance();

        //今日
        startday1 = DateUtil.getToday();
        endday1 = DateUtil.getToday();

        //昨日
        startday2 = DateUtil.addToday(-1);
        endday2 = DateUtil.addToday(-1);

        //本月
        endday3 = DateUtil.getToday();
        cal.setTime(today);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        startday3 = DateUtil.getToday(cal.getTime());

        String wsql1 = String.format("( date(paytime) >= '%s' and date(paytime) <= '%s' )", startday1, endday1);
        String wsql2 = String.format("( date(paytime) >= '%s' and date(paytime) <= '%s' )", startday2, endday2);
        String wsql3 = String.format("( date(paytime) >= '%s' and date(paytime) <= '%s' )", startday3, endday3);
        entity.where(datetype == 1 ? wsql1 : datetype == 2 ? wsql2 : wsql3);

        entity.orderBy("id", false);
        BigDecimal yeji1 = new BigDecimal(0);
        BigDecimal yeji2 = new BigDecimal(0);
        BigDecimal yeji3 = new BigDecimal(0);

        Map yjmap = new HashMap();
//        yjmap.put("yeji1", yeji1);
//        yjmap.put("yeji2", yeji2);
//        yjmap.put("yeji3", yeji3);
        jinfo.setExtra(yjmap);

        Page<Order> plist = orderService.selectPage(page, entity);
        if (plist == null || plist.getSize() == 0) {
            jinfo.setInfo(new ArrayList());
//            return jinfo;
        }

        List<Order> orders = plist.getRecords();

        for (Order o : orders) {
            map.clear();
            map.put("oid", o.getId());
            o.setList(orderGoodsService.selectByMap(map));
            if (o.getIsRefund() == 1)
                o.setOrderRefund(refundService.selectOne(new EntityWrapper<OrderRefund>()
                        .setSqlSelect("id,realpay,refund,order_no orderNo,refund_no refundNo,status")
                        .eq("oid", o.getId())));
        }

        jinfo.setInfo(orders);

        entity = new EntityWrapper<Order>()
                .eq("mpid", mpid)
                .eq("state", 1)
                .ge("gtype", 1)
                .ge("type", 1)
                .eq("fanuid", uid)
                .eq("xftype", XftypeEnum.buy.getVal())
                .eq("is_deleted", -1).setSqlSelect("sum(realpay) realpay");
        entity.where(wsql1);
        Order orderstat1 = orderService.selectOne(entity);
        yjmap.put("yeji1", orderstat1 == null || orderstat1.getRealpay() == null ? 0 : orderstat1.getRealpay().doubleValue());

        entity = new EntityWrapper<Order>()
                .eq("mpid", mpid)
                .eq("state", 1)
                .ge("gtype", 1)
                .ge("type", 1)
                .eq("fanuid", uid)
                .eq("xftype", XftypeEnum.buy.getVal())
                .eq("is_deleted", -1).setSqlSelect("sum(realpay) realpay");
        entity.where(wsql2);
        Order orderstat2 = orderService.selectOne(entity);
        yjmap.put("yeji2", orderstat2 == null || orderstat2.getRealpay() == null ? 0 : orderstat2.getRealpay().doubleValue());

        entity = new EntityWrapper<Order>()
                .eq("mpid", mpid)
                .eq("state", 1)
                .ge("gtype", 1)
                .ge("type", 1)
                .eq("fanuid", uid)
                .eq("xftype", XftypeEnum.buy.getVal())
                .eq("is_deleted", -1).setSqlSelect("sum(realpay) realpay");
        entity.where(wsql3);
        Order orderstat3 = orderService.selectOne(entity);
        yjmap.put("yeji3", orderstat3 == null || orderstat3.getRealpay() == null ? 0 : orderstat3.getRealpay().doubleValue());

        jinfo.setExtra(yjmap);
        return jinfo;
    }


    /*
     * 华口云专属
     * 门诊待核销+已核销订单列表
     */
    @RequestMapping("/api/order/mchhxlist")
    @ResponseBody
    public Jinfo mchhxlist(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                           @RequestParam(value = "status", required = false) Integer status,
                           @RequestParam(value = "pageSize", required = false) int pageSize) {
        Jinfo jinfo = new Jinfo();
        Map<String, Object> map = new HashMap<String, Object>();
        Long mpid = ObjectUtil.getMpid();
        Integer minstatus = 2;
        Integer maxstatus = 2;
        if (status == null || status == 5) {
            minstatus = 5;
            maxstatus = 5;
        } else {
            minstatus = 2;
            maxstatus = 4;
        }

        Page<Order> page = new Page<Order>(pageIndex, pageSize);
        Long sid = ObjectUtil.getSid();
        if (sid == null) {
            jinfo.setCode(1);
            jinfo.setMsg("参数有误");
            return jinfo;
        }

        Wrapper<Order> entity = new EntityWrapper<Order>()
                .eq("mpid", mpid)
                .eq("sid", sid)
                .eq("state", 1)
                .ge("status", minstatus)
                .ge("status", maxstatus)
                .ge("gtype", 3)
                .ge("type", 0)
                .eq("is_deleted", -1);

        Page<Order> plist = orderService.selectPage(page, entity);
        jinfo.setInfo(plist.getRecords());

        return jinfo;
    }

}

